Project

General

Profile

Download (58.5 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-2016 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
	7680 => "7680 bit",
87
	8192 => "8192 bit",
88
	15360 => "15360 bit",
89
	16384 => "16384 bit",
90
	"none" => "ECDH Only"
91
);
92
foreach ($openvpn_dh_lengths as $idx => $dhlen) {
93
	if (is_numeric($idx) && !file_exists("/etc/dh-parameters.{$idx}")) {
94
		unset($openvpn_dh_lengths[$idx]);
95
	}
96
}
97

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

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

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

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

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

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

    
143
global $openvpn_tls_modes;
144
$openvpn_tls_modes = array(
145
	'auth' => gettext("TLS Authentication"),
146
	'crypt' => gettext("TLS Encryption and Authentication")
147
);
148

    
149
function openvpn_build_mode_list() {
150
	global $openvpn_server_modes;
151

    
152
	$list = array();
153

    
154
	foreach ($openvpn_server_modes as $name => $desc) {
155
		$list[$name] = $desc;
156
	}
157

    
158
	return($list);
159
}
160

    
161
function openvpn_build_if_list() {
162
	$list = array();
163

    
164
	$interfaces = get_configured_interface_with_descr();
165
	$viplist = get_configured_vip_list();
166
	foreach ($viplist as $vip => $address) {
167
		$interfaces[$vip.'|'.$address] = $address;
168
		if (get_vip_descr($address)) {
169
			$interfaces[$vip.'|'.$address] .= " (";
170
			$interfaces[$vip.'|'.$address] .= get_vip_descr($address);
171
			$interfaces[$vip.'|'.$address] .= ")";
172
		}
173
	}
174

    
175
	$grouplist = return_gateway_groups_array();
176
	foreach ($grouplist as $name => $group) {
177
		if ($group[0]['vip'] != "") {
178
			$vipif = $group[0]['vip'];
179
		} else {
180
			$vipif = $group[0]['int'];
181
		}
182

    
183
		$interfaces[$name] = "GW Group {$name}";
184
	}
185

    
186
	$interfaces['lo0'] = "Localhost";
187
	$interfaces['any'] = "any";
188

    
189
	foreach ($interfaces as $iface => $ifacename) {
190
	   $list[$iface] = $ifacename;
191
	}
192

    
193
	return($list);
194
}
195

    
196
function openvpn_build_crl_list() {
197
	global $a_crl;
198

    
199
	$list = array('' => 'None');
200

    
201
	foreach ($a_crl as $crl) {
202
		$caname = "";
203
		$ca = lookup_ca($crl['caref']);
204

    
205
		if ($ca) {
206
			$caname = " (CA: {$ca['descr']})";
207
		}
208

    
209
		$list[$crl['refid']] = $crl['descr'] . $caname;
210
	}
211

    
212
	return($list);
213
}
214

    
215
function openvpn_build_cert_list($include_none = false, $prioritize_server_certs = false) {
216
	global $a_cert;
217

    
218
	if ($include_none) {
219
		$list = array('' => gettext('None (Username and/or Password required)'));
220
	} else {
221
		$list = array();
222
	}
223

    
224
	$non_server_list = array();
225

    
226
	if ($prioritize_server_certs) {
227
		$list[' '] = gettext("===== Server Certificates =====");
228
		$non_server_list['  '] = gettext("===== Non-Server Certificates =====");
229
	}
230

    
231
	foreach ($a_cert as $cert) {
232
		$properties = array();
233
		$propstr = "";
234
		$ca = lookup_ca($cert['caref']);
235
		$purpose = cert_get_purpose($cert['crt'], true);
236

    
237
		if ($purpose['server'] == "Yes") {
238
			$properties[] = gettext("Server: Yes");
239
		} elseif ($prioritize_server_certs) {
240
			$properties[] = gettext("Server: NO");
241
		}
242
		if ($ca) {
243
			$properties[] = sprintf(gettext("CA: %s"), $ca['descr']);
244
		}
245
		if (cert_in_use($cert['refid'])) {
246
			$properties[] = gettext("In Use");
247
		}
248
		if (is_cert_revoked($cert)) {
249
			$properties[] = gettext("Revoked");
250
		}
251

    
252
		if (!empty($properties)) {
253
			$propstr = " (" . implode(", ", $properties) . ")";
254
		}
255

    
256
		if ($prioritize_server_certs) {
257
			if ($purpose['server'] == "Yes") {
258
				$list[$cert['refid']] = $cert['descr'] . $propstr;
259
			} else {
260
				$non_server_list[$cert['refid']] = $cert['descr'] . $propstr;
261
			}
262
		} else {
263
			$list[$cert['refid']] = $cert['descr'] . $propstr;
264
		}
265
	}
266

    
267
	return(array('server' => $list, 'non-server' => $non_server_list));
268
}
269

    
270
function openvpn_build_bridge_list() {
271
	$list = array();
272

    
273
	$serverbridge_interface['none'] = "none";
274
	$serverbridge_interface = array_merge($serverbridge_interface, get_configured_interface_with_descr());
275
	$viplist = get_configured_vip_list();
276

    
277
	foreach ($viplist as $vip => $address) {
278
		$serverbridge_interface[$vip.'|'.$address] = $address;
279
		if (get_vip_descr($address)) {
280
			$serverbridge_interface[$vip.'|'.$address] .= " (". get_vip_descr($address) .")";
281
		}
282
	}
283

    
284
	foreach ($serverbridge_interface as $iface => $ifacename) {
285
		$list[$iface] = htmlspecialchars($ifacename);
286
	}
287

    
288
	return($list);
289
}
290

    
291
function openvpn_create_key() {
292

    
293
	$fp = popen("/usr/local/sbin/openvpn --genkey --secret /dev/stdout 2>/dev/null", "r");
294
	if (!$fp) {
295
		return false;
296
	}
297

    
298
	$rslt = stream_get_contents($fp);
299
	pclose($fp);
300

    
301
	return $rslt;
302
}
303

    
304
function openvpn_create_dhparams($bits) {
305

    
306
	$fp = popen("/usr/bin/openssl dhparam {$bits} 2>/dev/null", "r");
307
	if (!$fp) {
308
		return false;
309
	}
310

    
311
	$rslt = stream_get_contents($fp);
312
	pclose($fp);
313

    
314
	return $rslt;
315
}
316

    
317
function openvpn_vpnid_used($vpnid) {
318
	global $config;
319

    
320
	if (is_array($config['openvpn']['openvpn-server'])) {
321
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
322
			if ($vpnid == $settings['vpnid']) {
323
				return true;
324
			}
325
		}
326
	}
327

    
328
	if (is_array($config['openvpn']['openvpn-client'])) {
329
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
330
			if ($vpnid == $settings['vpnid']) {
331
				return true;
332
			}
333
		}
334
	}
335

    
336
	return false;
337
}
338

    
339
function openvpn_vpnid_next() {
340

    
341
	$vpnid = 1;
342
	while (openvpn_vpnid_used($vpnid)) {
343
		$vpnid++;
344
	}
345

    
346
	return $vpnid;
347
}
348

    
349
function openvpn_port_used($prot, $interface, $port, $curvpnid = 0) {
350
	global $config;
351

    
352
	$ovpn_settings = array();
353
	if (is_array($config['openvpn']['openvpn-server'])) {
354
		$ovpn_settings = $config['openvpn']['openvpn-server'];
355
	}
356
	if (is_array($config['openvpn']['openvpn-client'])) {
357
		$ovpn_settings = array_merge($ovpn_settings,
358
		    $config['openvpn']['openvpn-client']);
359
	}
360

    
361
	foreach ($ovpn_settings as $settings) {
362
		if (isset($settings['disable'])) {
363
			continue;
364
		}
365

    
366
		if ($curvpnid != 0 && $curvpnid == $settings['vpnid']) {
367
			continue;
368
		}
369

    
370
		/* (TCP|UDP)(4|6) does not conflict unless interface is any */
371
		if (($interface != "any" && $settings['interface'] != "any") &&
372
		    (strlen($prot) == 4) &&
373
		    (strlen($settings['protocol']) == 4) &&
374
		    substr($prot,0,3) == substr($settings['protocol'],0,3) &&
375
		    substr($prot,3,1) != substr($settings['protocol'],3,1)) {
376
			continue;
377
		}
378

    
379
		if ($port == $settings['local_port'] &&
380
		    substr($prot,0,3) == substr($settings['protocol'],0,3) &&
381
		    ($interface == $settings['interface'] ||
382
		    $interface == "any" || $settings['interface'] == "any")) {
383
			return $settings['vpnid'];
384
		}
385
	}
386

    
387
	return 0;
388
}
389

    
390
function openvpn_port_next($prot, $interface = "wan") {
391

    
392
	$port = 1194;
393
	while (openvpn_port_used($prot, $interface, $port)) {
394
		$port++;
395
	}
396
	while (openvpn_port_used($prot, "any", $port)) {
397
		$port++;
398
	}
399

    
400
	return $port;
401
}
402

    
403
function openvpn_get_cipherlist() {
404

    
405
	$ciphers = array();
406
	$cipher_out = shell_exec('/usr/local/sbin/openvpn --show-ciphers | /usr/bin/grep \'(.*key\' | sed \'s/, TLS client\/server mode only//\'');
407
	$cipher_lines = explode("\n", trim($cipher_out));
408
	sort($cipher_lines);
409
	foreach ($cipher_lines as $line) {
410
		$words = explode(' ', $line, 2);
411
		$ciphers[$words[0]] = "{$words[0]} {$words[1]}";
412
	}
413
	$ciphers["none"] = gettext("None (No Encryption)");
414
	return $ciphers;
415
}
416

    
417
function openvpn_get_curvelist() {
418

    
419
	$curves = array();
420
	$curves["none"] = gettext("Use Default");
421
	$curve_out = shell_exec('/usr/local/sbin/openvpn --show-curves | /usr/bin/grep -v \'Available Elliptic curves\'');
422
	$curve_lines = explode("\n", trim($curve_out));
423
	sort($curve_lines);
424
	foreach ($curve_lines as $line) {
425
		$line = trim($line);
426
		$curves[$line] = $line;
427
	}
428
	return $curves;
429
}
430

    
431
function openvpn_validate_curve($curve) {
432
	$curves = openvpn_get_curvelist();
433
	return array_key_exists($curve, $curves);
434
}
435

    
436
/* Obtain the list of digest algorithms supported by openssl and their alternate names */
437
function openvpn_get_openssldigestmappings() {
438
	$digests = array();
439
	$digest_out = shell_exec('/usr/bin/openssl list-message-digest-algorithms | /usr/bin/grep "=>"');
440
	$digest_lines = explode("\n", trim($digest_out));
441
	sort($digest_lines);
442
	foreach ($digest_lines as $line) {
443
		$words = explode(' => ', $line, 2);
444
		$digests[$words[0]] = $words[1];
445
	}
446
	return $digests;
447
}
448

    
449
/* Obtain the list of digest algorithms supported by openvpn */
450
function openvpn_get_digestlist() {
451
	/* Grab the list from OpenSSL to check for duplicates or aliases */
452
	$openssl_digest_mappings = openvpn_get_openssldigestmappings();
453
	$digests = array();
454
	$digest_out = shell_exec('/usr/local/sbin/openvpn --show-digests | /usr/bin/grep "digest size" | /usr/bin/awk \'{print $1, "(" $2 "-" $3 ")";}\'');
455
	$digest_lines = explode("\n", trim($digest_out));
456
	sort($digest_lines);
457
	foreach ($digest_lines as $line) {
458
		$words = explode(' ', $line);
459
		/* Only add the entry if it is NOT also listed as being an alias/mapping by OpenSSL */
460
		if (!array_key_exists($words[0], $openssl_digest_mappings)) {
461
			$digests[$words[0]] = "{$words[0]} {$words[1]}";
462
		}
463
	}
464
	$digests["none"] = gettext("None (No Authentication)");
465
	return $digests;
466
}
467

    
468
/* Check to see if a digest name is an alias and if so, find the actual digest
469
 * algorithm instead. Useful for upgrade code that has to translate aliased
470
 * algorithms to their actual names.
471
 */
472
function openvpn_remap_digest($digest) {
473
	$openssl_digest_mappings = openvpn_get_openssldigestmappings();
474
	if (array_key_exists($digest, $openssl_digest_mappings)) {
475
		/* Some mappings point to other mappings, keep going until we find the actual digest algorithm */
476
		if (array_key_exists($openssl_digest_mappings[$digest], $openssl_digest_mappings)) {
477
			return openvpn_remap_digest($openssl_digest_mappings[$digest]);
478
		} else {
479
			return $openssl_digest_mappings[$digest];
480
		}
481
	}
482
	return $digest;
483
}
484

    
485
function openvpn_get_engines() {
486
	$openssl_engines = array('none' => gettext('No Hardware Crypto Acceleration'));
487
	exec("/usr/bin/openssl engine -t -c", $openssl_engine_output);
488
	$openssl_engine_output = implode("\n", $openssl_engine_output);
489
	$openssl_engine_output = preg_replace("/\\n\\s+/", "|", $openssl_engine_output);
490
	$openssl_engine_output = explode("\n", $openssl_engine_output);
491

    
492
	foreach ($openssl_engine_output as $oeo) {
493
		$keep = true;
494
		$details = explode("|", $oeo);
495
		$engine = array_shift($details);
496
		$linematch = array();
497
		preg_match("/\((.*)\)\s(.*)/", $engine, $linematch);
498
		foreach ($details as $dt) {
499
			if (strpos($dt, "unavailable") !== FALSE) {
500
				$keep = false;
501
			}
502
			if (strpos($dt, "available") !== FALSE) {
503
				continue;
504
			}
505
			if (strpos($dt, "[") !== FALSE) {
506
				$ciphers = trim($dt, "[]");
507
			}
508
		}
509
		if (!empty($ciphers)) {
510
			$ciphers = " - " . $ciphers;
511
		}
512
		if (strlen($ciphers) > 60) {
513
			$ciphers = substr($ciphers, 0, 60) . " ... ";
514
		}
515
		if ($keep) {
516
			$openssl_engines[$linematch[1]] = $linematch[2] . $ciphers;
517
		}
518
	}
519
	return $openssl_engines;
520
}
521

    
522
function openvpn_get_buffer_values() {
523
	$sendbuf_max = get_single_sysctl('net.inet.tcp.sendbuf_max');
524
	$recvbuf_max = get_single_sysctl('net.inet.tcp.recvbuf_max');
525
	/* Usually these two are equal, but if they are not, take whichever one is lower. */
526
	$buffer_max = ($sendbuf_max <= $recvbuf_max) ? $sendbuf_max : $recvbuf_max;
527
	$buffer_values = array('' => gettext('Default'));
528
	for ($bs = 32; $bs >= 1; $bs /= 2) {
529
		$buffer_values[$buffer_max/$bs] = format_bytes($buffer_max/$bs);
530
	}
531
	return $buffer_values;
532
}
533

    
534
function openvpn_validate_engine($engine) {
535
	$engines = openvpn_get_engines();
536
	return array_key_exists($engine, $engines);
537
}
538

    
539
function openvpn_validate_host($value, $name) {
540
	$value = trim($value);
541
	if (empty($value) || (!is_domain($value) && !is_ipaddr($value))) {
542
		return sprintf(gettext("The field '%s' must contain a valid IP address or domain name."), $name);
543
	}
544
	return false;
545
}
546

    
547
function openvpn_validate_port($value, $name, $first_port = 0) {
548
	$value = trim($value);
549
	if (!is_numeric($first_port)) {
550
		$first_port = 0;
551
	}
552
	if (empty($value) || !is_numeric($value) || $value < $first_port || ($value > 65535)) {
553
		return sprintf(gettext("The field '%s' must contain a valid port, ranging from {$first_port} to 65535."), $name);
554
	}
555
	return false;
556
}
557

    
558
function openvpn_validate_cidr($value, $name, $multiple = false, $ipproto = "ipv4") {
559
	$value = trim($value);
560
	$error = false;
561
	if (empty($value)) {
562
		return false;
563
	}
564
	$networks = explode(',', $value);
565

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

    
570
	foreach ($networks as $network) {
571
		if ($ipproto == "ipv4") {
572
			$error = !openvpn_validate_cidr_ipv4($network);
573
		} else {
574
			$error = !openvpn_validate_cidr_ipv6($network);
575
		}
576
		if ($error) {
577
			break;
578
		}
579
	}
580

    
581
	if ($error) {
582
		return sprintf(gettext("The field '%1\$s' must contain only valid %2\$s CIDR range(s) separated by commas."), $name, $ipproto);
583
	} else {
584
		return false;
585
	}
586
}
587

    
588
function openvpn_validate_cidr_ipv4($value) {
589
	$value = trim($value);
590
	if (!empty($value)) {
591
		list($ip, $mask) = explode('/', $value);
592
		if (!is_ipaddrv4($ip) or !is_numeric($mask) or ($mask > 32) or ($mask < 0)) {
593
			return false;
594
		}
595
	}
596
	return true;
597
}
598

    
599
function openvpn_validate_cidr_ipv6($value) {
600
	$value = trim($value);
601
	if (!empty($value)) {
602
		list($ipv6, $prefix) = explode('/', $value);
603
		if (empty($prefix)) {
604
			$prefix = "128";
605
		}
606
		if (!is_ipaddrv6($ipv6) or !is_numeric($prefix) or ($prefix > 128) or ($prefix < 0)) {
607
			return false;
608
		}
609
	}
610
	return true;
611
}
612

    
613
function openvpn_add_dhcpopts(& $settings, & $conf) {
614

    
615
	if (!empty($settings['dns_domain'])) {
616
		$conf .= "push \"dhcp-option DOMAIN {$settings['dns_domain']}\"\n";
617
	}
618

    
619
	if (!empty($settings['dns_server1'])) {
620
		$dnstype = (is_ipaddrv6($settings['dns_server1'])) ? "DNS6" : "DNS";
621
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server1']}\"\n";
622
	}
623
	if (!empty($settings['dns_server2'])) {
624
		$dnstype = (is_ipaddrv6($settings['dns_server2'])) ? "DNS6" : "DNS";
625
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server2']}\"\n";
626
	}
627
	if (!empty($settings['dns_server3'])) {
628
		$dnstype = (is_ipaddrv6($settings['dns_server3'])) ? "DNS6" : "DNS";
629
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server3']}\"\n";
630
	}
631
	if (!empty($settings['dns_server4'])) {
632
		$dnstype = (is_ipaddrv6($settings['dns_server4'])) ? "DNS6" : "DNS";
633
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server4']}\"\n";
634
	}
635

    
636
	if (!empty($settings['push_blockoutsidedns'])) {
637
		$conf .= "push \"block-outside-dns\"\n";
638
	}
639
	if (!empty($settings['push_register_dns'])) {
640
		$conf .= "push \"register-dns\"\n";
641
	}
642

    
643
	if (!empty($settings['ntp_server1'])) {
644
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server1']}\"\n";
645
	}
646
	if (!empty($settings['ntp_server2'])) {
647
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server2']}\"\n";
648
	}
649

    
650
	if ($settings['netbios_enable']) {
651

    
652
		if (!empty($settings['dhcp_nbttype']) && ($settings['dhcp_nbttype'] != 0)) {
653
			$conf .= "push \"dhcp-option NBT {$settings['dhcp_nbttype']}\"\n";
654
		}
655
		if (!empty($settings['dhcp_nbtscope'])) {
656
			$conf .= "push \"dhcp-option NBS {$settings['dhcp_nbtscope']}\"\n";
657
		}
658

    
659
		if (!empty($settings['wins_server1'])) {
660
			$conf .= "push \"dhcp-option WINS {$settings['wins_server1']}\"\n";
661
		}
662
		if (!empty($settings['wins_server2'])) {
663
			$conf .= "push \"dhcp-option WINS {$settings['wins_server2']}\"\n";
664
		}
665

    
666
		if (!empty($settings['nbdd_server1'])) {
667
			$conf .= "push \"dhcp-option NBDD {$settings['nbdd_server1']}\"\n";
668
		}
669
	}
670

    
671
	if ($settings['gwredir']) {
672
		$conf .= "push \"redirect-gateway def1\"\n";
673
	}
674
}
675

    
676
function openvpn_add_custom(& $settings, & $conf) {
677

    
678
	if ($settings['custom_options']) {
679

    
680
		$options = explode(';', $settings['custom_options']);
681

    
682
		if (is_array($options)) {
683
			foreach ($options as $option) {
684
				$conf .= "$option\n";
685
			}
686
		} else {
687
			$conf .= "{$settings['custom_options']}\n";
688
		}
689
	}
690
}
691

    
692
function openvpn_add_keyfile(& $data, & $conf, $mode_id, $directive, $opt = "") {
693
	global $g;
694

    
695
	$fpath = $g['varetc_path']."/openvpn/{$mode_id}.{$directive}";
696
	openvpn_create_dirs();
697
	file_put_contents($fpath, base64_decode($data));
698
	//chown($fpath, 'nobody');
699
	//chgrp($fpath, 'nobody');
700
	@chmod($fpath, 0600);
701

    
702
	$conf .= "{$directive} {$fpath} {$opt}\n";
703
}
704

    
705
function openvpn_reconfigure($mode, $settings) {
706
	global $g, $config, $openvpn_tls_server_modes, $openvpn_dh_lengths;
707

    
708
	if (empty($settings)) {
709
		return;
710
	}
711
	if (isset($settings['disable'])) {
712
		return;
713
	}
714
	openvpn_create_dirs();
715
	/*
716
	 * NOTE: Deleting tap devices causes spontaneous reboots. Instead,
717
	 * we use a vpnid number which is allocated for a particular client
718
	 * or server configuration. ( see openvpn_vpnid_next() )
719
	 */
720

    
721
	$vpnid = $settings['vpnid'];
722
	$mode_id = $mode.$vpnid;
723

    
724
	if (isset($settings['dev_mode'])) {
725
		$tunname = "{$settings['dev_mode']}{$vpnid}";
726
	} else {
727
		/* defaults to tun */
728
		$tunname = "tun{$vpnid}";
729
		$settings['dev_mode'] = "tun";
730
	}
731

    
732
	if ($mode == "server") {
733
		$devname = "ovpns{$vpnid}";
734
	} else {
735
		$devname = "ovpnc{$vpnid}";
736
	}
737

    
738
	/* is our device already configured */
739
	if (!does_interface_exist($devname)) {
740

    
741
		/* create the tap device if required */
742
		if (!file_exists("/dev/{$tunname}")) {
743
			exec("/sbin/ifconfig " . escapeshellarg($tunname) . " create");
744
		}
745

    
746
		/* rename the device */
747
		mwexec("/sbin/ifconfig " . escapeshellarg($tunname) . " name " . escapeshellarg($devname));
748

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

    
752
		$ifname = convert_real_interface_to_friendly_interface_name($devname);
753
		$grouptmp = link_interface_to_group($ifname);
754
		if (!empty($grouptmp)) {
755
			array_walk($grouptmp, 'interface_group_add_member');
756
		}
757
		unset($grouptmp, $ifname);
758
	}
759

    
760
	$pfile = $g['varrun_path'] . "/openvpn_{$mode_id}.pid";
761
	$proto = strtolower($settings['protocol']);
762
	if (substr($settings['protocol'], 0, 3) == "TCP") {
763
			$proto = "{$proto}-{$mode}";
764
	}
765
	$dev_mode = $settings['dev_mode'];
766
	$cipher = $settings['crypto'];
767
	// OpenVPN defaults to SHA1, so use it when unset to maintain compatibility.
768
	$digest = !empty($settings['digest']) ? $settings['digest'] : "SHA1";
769

    
770
	$interface = get_failover_interface($settings['interface']);
771
	// The IP address in the settings can be an IPv4 or IPv6 address associated with the interface
772
	$ipaddr = $settings['ipaddr'];
773

    
774
	// If a specific ip address (VIP) is requested, use it.
775
	// Otherwise, if a specific interface is requested, use it
776
	// If "any" interface was selected, local directive will be omitted.
777
	if (is_ipaddrv4($ipaddr)) {
778
		$iface_ip = $ipaddr;
779
	} elseif (!empty($interface) && strcmp($interface, "any")) {
780
		$iface_ip=get_interface_ip($interface);
781
	}
782
	if (is_ipaddrv6($ipaddr)) {
783
		$iface_ipv6 = $ipaddr;
784
	} elseif (!empty($interface) && strcmp($interface, "any")) {
785
		$iface_ipv6=get_interface_ipv6($interface);
786
	}
787

    
788
	$conf = "dev {$devname}\n";
789
	if (isset($settings['verbosity_level'])) {
790
		$conf .= "verb {$settings['verbosity_level']}\n";
791
	}
792

    
793
	$conf .= "dev-type {$settings['dev_mode']}\n";
794
	$conf .= "dev-node /dev/{$tunname}\n";
795
	$conf .= "writepid {$pfile}\n";
796
	$conf .= "#user nobody\n";
797
	$conf .= "#group nobody\n";
798
	$conf .= "script-security 3\n";
799
	$conf .= "daemon\n";
800
	$conf .= "keepalive 10 60\n";
801
	$conf .= "ping-timer-rem\n";
802
	$conf .= "persist-tun\n";
803
	$conf .= "persist-key\n";
804
	$conf .= "proto {$proto}\n";
805
	$conf .= "cipher {$cipher}\n";
806
	$conf .= "auth {$digest}\n";
807
	$conf .= "up /usr/local/sbin/ovpn-linkup\n";
808
	$conf .= "down /usr/local/sbin/ovpn-linkdown\n";
809
	if (file_exists("/usr/local/sbin/openvpn.attributes.sh")) {
810
		switch ($settings['mode']) {
811
			case 'server_user':
812
			case 'server_tls_user':
813
				$conf .= "client-connect /usr/local/sbin/openvpn.attributes.sh\n";
814
				$conf .= "client-disconnect /usr/local/sbin/openvpn.attributes.sh\n";
815
				break;
816
		}
817
	}
818

    
819
	/*
820
	 * When binding specific address, wait cases where interface is in
821
	 * tentative state otherwise it will fail
822
	 */
823
	$wait_tentative = false;
824

    
825
	/* Determine the local IP to use - and make sure it matches with the selected protocol. */
826
	switch ($settings['protocol']) {
827
		case 'UDP':
828
		case 'TCP':
829
			$conf .= "multihome\n";
830
			break;
831
		case 'UDP4':
832
		case 'TCP4':
833
			if (is_ipaddrv4($iface_ip)) {
834
				$conf .= "local {$iface_ip}\n";
835
			}
836
			if ($settings['interface'] == "any") {
837
				$conf .= "multihome\n";
838
			}
839
			break;
840
		case 'UDP6':
841
		case 'TCP6':
842
			if (is_ipaddrv6($iface_ipv6)) {
843
				$conf .= "local {$iface_ipv6}\n";
844
				$wait_tentative = true;
845
			}
846
			if ($settings['interface'] == "any") {
847
				$conf .= "multihome\n";
848
			}
849
			break;
850
		default:
851
	}
852

    
853
	if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none")) {
854
		$conf .= "engine {$settings['engine']}\n";
855
	}
856

    
857
	// server specific settings
858
	if ($mode == 'server') {
859

    
860
		list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
861
		list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
862
		$mask = gen_subnet_mask($cidr);
863

    
864
		// configure tls modes
865
		switch ($settings['mode']) {
866
			case 'p2p_tls':
867
			case 'server_tls':
868
			case 'server_user':
869
			case 'server_tls_user':
870
				$conf .= "tls-server\n";
871
				break;
872
		}
873

    
874
		// configure p2p/server modes
875
		switch ($settings['mode']) {
876
			case 'p2p_tls':
877
				// If the CIDR is less than a /30, OpenVPN will complain if you try to
878
				//  use the server directive. It works for a single client without it.
879
				//  See ticket #1417
880
				if (!empty($ip) && !empty($mask) && ($cidr < 30)) {
881
					$conf .= "server {$ip} {$mask}\n";
882
					$conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc/server{$vpnid}\n";
883
					if (is_ipaddr($ipv6)) {
884
						$conf .= "server-ipv6 {$ipv6}/{$prefix}\n";
885
					}
886
				}
887
			case 'p2p_shared_key':
888
				if (!empty($ip) && !empty($mask)) {
889
					list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
890
					if ($settings['dev_mode'] == 'tun') {
891
						$conf .= "ifconfig {$ip1} {$ip2}\n";
892
					} else {
893
						$conf .= "ifconfig {$ip1} {$mask}\n";
894
					}
895
				}
896
				if (!empty($ipv6) && !empty($prefix)) {
897
					list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
898
					if ($settings['dev_mode'] == 'tun') {
899
						$conf .= "ifconfig-ipv6 {$ipv6_1} {$ipv6_2}\n";
900
					} else {
901
						$conf .= "ifconfig-ipv6 {$ipv6_1} {$prefix}\n";
902
					}
903
				}
904
				break;
905
			case 'server_tls':
906
			case 'server_user':
907
			case 'server_tls_user':
908
				if (!empty($ip) && !empty($mask)) {
909
					$conf .= "server {$ip} {$mask}\n";
910
					if (is_ipaddr($ipv6)) {
911
						$conf .= "server-ipv6 {$ipv6}/{$prefix}\n";
912
					}
913
					$conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc/server{$vpnid}\n";
914
				} else {
915
					if ($settings['serverbridge_dhcp']) {
916
						if ((!empty($settings['serverbridge_interface'])) && (strcmp($settings['serverbridge_interface'], "none"))) {
917
							$biface_ip=get_interface_ip($settings['serverbridge_interface']);
918
							$biface_sm=gen_subnet_mask(get_interface_subnet($settings['serverbridge_interface']));
919
							if (is_ipaddrv4($biface_ip) && is_ipaddrv4($settings['serverbridge_dhcp_start']) && is_ipaddrv4($settings['serverbridge_dhcp_end'])) {
920
								$conf .= "server-bridge {$biface_ip} {$biface_sm} {$settings['serverbridge_dhcp_start']} {$settings['serverbridge_dhcp_end']}\n";
921
								$conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc/server{$vpnid}\n";
922
							} else {
923
								$conf .= "mode server\n";
924
							}
925
						} else {
926
							$conf .= "mode server\n";
927
						}
928
					}
929
				}
930
				break;
931
		}
932

    
933
		// configure user auth modes
934
		switch ($settings['mode']) {
935
			case 'server_user':
936
				$conf .= "verify-client-cert none\n";
937
			case 'server_tls_user':
938
				/* username-as-common-name is not compatible with server-bridge */
939
				if (stristr($conf, "server-bridge") === false) {
940
					$conf .= "username-as-common-name\n";
941
				}
942
				if (!empty($settings['authmode'])) {
943
					$strictusercn = "false";
944
					if ($settings['strictusercn']) {
945
						$strictusercn = "true";
946
					}
947
					$conf .= "auth-user-pass-verify \"/usr/local/sbin/ovpn_auth_verify user " . base64_encode($settings['authmode']) . " {$strictusercn} {$mode_id} {$settings['local_port']}\" via-env\n";
948
				}
949
				break;
950
		}
951
		if (!isset($settings['cert_depth']) && (strstr($settings['mode'], 'tls'))) {
952
			$settings['cert_depth'] = 1;
953
		}
954
		if (is_numeric($settings['cert_depth'])) {
955
			if (($mode == 'client') && empty($settings['certref'])) {
956
				$cert = "";
957
			} else {
958
				$cert = lookup_cert($settings['certref']);
959
				/* XXX: Seems not used at all! */
960
				$servercn = urlencode(cert_get_cn($cert['crt']));
961
				$conf .= "tls-verify \"/usr/local/sbin/ovpn_auth_verify tls '{$servercn}' {$settings['cert_depth']}\"\n";
962
			}
963
		}
964

    
965
		// The local port to listen on
966
		$conf .= "lport {$settings['local_port']}\n";
967

    
968
		// The management port to listen on
969
		// Use unix socket to overcome the problem on any type of server
970
		$conf .= "management {$g['varetc_path']}/openvpn/{$mode_id}.sock unix\n";
971
		//$conf .= "management 127.0.0.1 {$settings['local_port']}\n";
972

    
973
		if ($settings['maxclients']) {
974
			$conf .= "max-clients {$settings['maxclients']}\n";
975
		}
976

    
977
		// Can we push routes
978
		if ($settings['local_network']) {
979
			$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
980
		}
981
		if ($settings['local_networkv6']) {
982
			$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
983
		}
984

    
985
		switch ($settings['mode']) {
986
			case 'server_tls':
987
			case 'server_user':
988
			case 'server_tls_user':
989
				// Configure client dhcp options
990
				openvpn_add_dhcpopts($settings, $conf);
991
				if ($settings['client2client']) {
992
					$conf .= "client-to-client\n";
993
				}
994
				break;
995
		}
996
		if (isset($settings['duplicate_cn'])) {
997
			$conf .= "duplicate-cn\n";
998
		}
999
	}
1000

    
1001
	// client specific settings
1002

    
1003
	if ($mode == 'client') {
1004

    
1005
		// configure p2p mode
1006
		switch ($settings['mode']) {
1007
			case 'p2p_tls':
1008
				$conf .= "tls-client\n";
1009
			case 'shared_key':
1010
				$conf .= "client\n";
1011
				break;
1012
		}
1013

    
1014
		// If there is no bind option at all (ip and/or port), add "nobind" directive
1015
		//  Otherwise, use the local port if defined, failing that, use lport 0 to
1016
		//  ensure a random source port.
1017
		if ((empty($iface_ip)) && empty($iface_ipv6) && (!$settings['local_port'])) {
1018
			$conf .= "nobind\n";
1019
		} elseif ($settings['local_port']) {
1020
			$conf .= "lport {$settings['local_port']}\n";
1021
		} else {
1022
			$conf .= "lport 0\n";
1023
		}
1024

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

    
1028
		// The remote server
1029
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']}\n";
1030

    
1031
		if (!empty($settings['use_shaper'])) {
1032
			$conf .= "shaper {$settings['use_shaper']}\n";
1033
		}
1034

    
1035
		if (!empty($settings['tunnel_network'])) {
1036
			list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
1037
			$mask = gen_subnet_mask($cidr);
1038
			list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1039
			if ($settings['dev_mode'] == 'tun') {
1040
				$conf .= "ifconfig {$ip2} {$ip1}\n";
1041
			} else {
1042
				$conf .= "ifconfig {$ip2} {$mask}\n";
1043
			}
1044
		}
1045

    
1046
		if (!empty($settings['tunnel_networkv6'])) {
1047
			list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
1048
			list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1049
			if ($settings['dev_mode'] == 'tun') {
1050
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$ipv6_1}\n";
1051
			} else {
1052
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$prefix}\n";
1053
			}
1054
		}
1055

    
1056
		if (($settings['auth_user'] || $settings['auth_pass']) && $settings['mode'] == "p2p_tls") {
1057
			$up_file = "{$g['varetc_path']}/openvpn/{$mode_id}.up";
1058
			$conf .= "auth-user-pass {$up_file}\n";
1059
			if (!$settings['auth-retry-none']) {
1060
				$conf .= "auth-retry nointeract\n";
1061
			}
1062
			if ($settings['auth_user']) {
1063
				$userpass = "{$settings['auth_user']}\n";
1064
			} else {
1065
				$userpass = "";
1066
			}
1067
			if ($settings['auth_pass']) {
1068
				$userpass .= "{$settings['auth_pass']}\n";
1069
			}
1070
			// If only auth_pass is given, then it acts like a user name and we put a blank line where pass would normally go.
1071
			if (!($settings['auth_user'] && $settings['auth_pass'])) {
1072
				$userpass .= "\n";
1073
			}
1074
			file_put_contents($up_file, $userpass);
1075
		}
1076

    
1077
		if ($settings['proxy_addr']) {
1078
			$conf .= "http-proxy {$settings['proxy_addr']} {$settings['proxy_port']}";
1079
			if ($settings['proxy_authtype'] != "none") {
1080
				$conf .= " {$g['varetc_path']}/openvpn/{$mode_id}.pas {$settings['proxy_authtype']}";
1081
				$proxypas = "{$settings['proxy_user']}\n";
1082
				$proxypas .= "{$settings['proxy_passwd']}\n";
1083
				file_put_contents("{$g['varetc_path']}/openvpn/{$mode_id}.pas", $proxypas);
1084
			}
1085
			$conf .= " \n";
1086
		}
1087
	}
1088

    
1089
	// Add a remote network route if set, and only for p2p modes.
1090
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE)) {
1091
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false);
1092
	}
1093
	// Add a remote network route if set, and only for p2p modes.
1094
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE)) {
1095
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false);
1096
	}
1097

    
1098
	// Write the settings for the keys
1099
	switch ($settings['mode']) {
1100
		case 'p2p_shared_key':
1101
			openvpn_add_keyfile($settings['shared_key'], $conf, $mode_id, "secret");
1102
			break;
1103
		case 'p2p_tls':
1104
		case 'server_tls':
1105
		case 'server_tls_user':
1106
		case 'server_user':
1107
			// ca_chain() expects parameter to be passed by reference. 
1108
			// avoid passing the whole settings array, as param names or 
1109
			// types might change in future releases. 
1110
			$param = array('caref' => $settings['caref']);	
1111
			$ca = ca_chain($param);
1112
			$ca = base64_encode($ca);
1113
			
1114
			openvpn_add_keyfile($ca, $conf, $mode_id, "ca");
1115
			
1116
			unset($ca, $param);
1117

    
1118
			if (!empty($settings['certref'])) {
1119
				$cert = lookup_cert($settings['certref']);
1120
				openvpn_add_keyfile($cert['crt'], $conf, $mode_id, "cert");
1121
				openvpn_add_keyfile($cert['prv'], $conf, $mode_id, "key");
1122
			}
1123
			if ($mode == 'server') {
1124
				if (is_numeric($settings['dh_length'])) {
1125
					if (!in_array($settings['dh_length'], array_keys($openvpn_dh_lengths))) {
1126
						/* The user selected a DH parameter length that does not have a corresponding file. */
1127
						log_error(gettext("Failed to construct OpenVPN server configuration. The selected DH Parameter length cannot be used."));
1128
						return;
1129
					}
1130
					$dh_file = "{$g['etc_path']}/dh-parameters.{$settings['dh_length']}";
1131
				} else {
1132
					$dh_file = $settings['dh_length'];
1133
				}
1134
				$conf .= "dh {$dh_file}\n";
1135
				if (!empty($settings['ecdh_curve']) && ($settings['ecdh_curve'] != "none") && openvpn_validate_curve($settings['ecdh_curve'])) {
1136
					$conf .= "ecdh-curve {$settings['ecdh_curve']}\n";
1137
				}
1138
			}
1139
			if (!empty($settings['crlref'])) {
1140
				$crl = lookup_crl($settings['crlref']);
1141
				crl_update($crl);
1142
				openvpn_add_keyfile($crl['text'], $conf, $mode_id, "crl-verify");
1143
			}
1144
			if ($settings['tls']) {
1145
				if ($settings['tls_type'] == "crypt") {
1146
					$tls_directive = "tls-crypt";
1147
					$tlsopt = "";
1148
				} else {
1149
					$tls_directive = "tls-auth";
1150
					if ($mode == "server") {
1151
						$tlsopt = 0;
1152
					} else {
1153
						$tlsopt = 1;
1154
					}
1155
				}
1156
				openvpn_add_keyfile($settings['tls'], $conf, $mode_id, $tls_directive, $tlsopt);
1157
			}
1158

    
1159
			/* NCP support. If it is not set, assume enabled since that is OpenVPN's default. */
1160
			if ($settings['ncp_enable'] == "disabled") {
1161
				$conf .= "ncp-disable\n";
1162
			} else {
1163
				/* If the ncp-ciphers list is empty, don't specify a list so OpenVPN's default will be used. */
1164
				if (!empty($settings['ncp-ciphers'])) {
1165
					$conf .= "ncp-ciphers " . str_replace(',', ':', $settings['ncp-ciphers']) . "\n";
1166
				}
1167
			}
1168

    
1169
			break;
1170
	}
1171

    
1172
	$compression = "";
1173
	switch ($settings['compression']) {
1174
		case 'lz4':
1175
		case 'lz4-v2':
1176
		case 'lzo':
1177
		case 'stub':
1178
			$compression .= "compress {$settings['compression']}";
1179
			break;
1180
		case 'noadapt':
1181
			$compression .= "comp-noadapt";
1182
			break;
1183
		case 'adaptive':
1184
		case 'yes':
1185
		case 'no':
1186
			$compression .= "comp-lzo {$settings['compression']}";
1187
			break;
1188
		default:
1189
			/* Add nothing to the configuration */
1190
			break;
1191
	}
1192

    
1193
	if (!empty($compression)) {
1194
		$conf .= "{$compression}\n";
1195
		if ($settings['compression_push']) {
1196
			$conf .= "push \"{$compression}\"\n";
1197
		}
1198
	}
1199

    
1200
	if ($settings['passtos']) {
1201
		$conf .= "passtos\n";
1202
	}
1203

    
1204
	if ($mode == 'client') {
1205
		$conf .= "resolv-retry infinite\n";
1206
	}
1207

    
1208
	if ($settings['dynamic_ip']) {
1209
		$conf .= "persist-remote-ip\n";
1210
		$conf .= "float\n";
1211
	}
1212

    
1213
	// If the server is not a TLS server or it has a tunnel network CIDR less than a /30, skip this.
1214
	if (in_array($settings['mode'], $openvpn_tls_server_modes) && (!empty($ip) && !empty($mask) && ($cidr < 30)) && $settings['dev_mode'] != "tap") {
1215
		if (empty($settings['topology'])) {
1216
			$settings['topology'] = "subnet";
1217
		}
1218
		$conf .= "topology {$settings['topology']}\n";
1219
	}
1220

    
1221
	// New client features
1222
	if ($mode == "client") {
1223
		// Dont pull routes checkbox
1224
		if ($settings['route_no_pull']) {
1225
			$conf .= "route-nopull\n";
1226
		}
1227

    
1228
		// Dont add/remove routes checkbox
1229
		if ($settings['route_no_exec']) {
1230
			$conf .= "route-noexec\n";
1231
		}
1232
	}
1233

    
1234
	/* UDP Fast I/O. Only compatible with UDP and also not compatible with OpenVPN's "shaper" directive. */
1235
	if ($settings['udp_fast_io']
1236
	    && (strtolower(substr($settings['protocol'], 0, 3)) == "udp")
1237
	    && (empty($settings['use_shaper']))) {
1238
		$conf .= "fast-io\n";
1239
	}
1240

    
1241
	/* Send and Receive Buffer Settings */
1242
	if (is_numericint($settings['sndrcvbuf'])
1243
	    && ($settings['sndrcvbuf'] > 0)
1244
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.sendbuf_max'))
1245
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.recvbuf_max'))) {
1246
		$conf .= "sndbuf {$settings['sndrcvbuf']}\n";
1247
		$conf .= "rcvbuf {$settings['sndrcvbuf']}\n";
1248
	}
1249

    
1250
	openvpn_add_custom($settings, $conf);
1251

    
1252
	openvpn_create_dirs();
1253
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.conf";
1254
	file_put_contents($fpath, $conf);
1255
	unset($conf);
1256
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.interface";
1257
	file_put_contents($fpath, $interface);
1258
	//chown($fpath, 'nobody');
1259
	//chgrp($fpath, 'nobody');
1260
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1261
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.interface", 0600);
1262
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.key", 0600);
1263
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.tls-auth", 0600);
1264
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1265

    
1266
	if ($wait_tentative) {
1267
		interface_wait_tentative($interface);
1268
	}
1269
}
1270

    
1271
function openvpn_restart($mode, $settings) {
1272
	global $g, $config;
1273

    
1274
	$vpnid = $settings['vpnid'];
1275
	$mode_id = $mode.$vpnid;
1276
	$lockhandle = lock("openvpnservice{$mode_id}", LOCK_EX);
1277
	openvpn_reconfigure($mode, $settings);
1278
	/* kill the process if running */
1279
	$pfile = $g['varrun_path']."/openvpn_{$mode_id}.pid";
1280
	if (file_exists($pfile)) {
1281

    
1282
		/* read the pid file */
1283
		$pid = rtrim(file_get_contents($pfile));
1284
		unlink($pfile);
1285
		syslog(LOG_INFO, "OpenVPN terminate old pid: {$pid}");
1286

    
1287
		/* send a term signal to the process */
1288
		posix_kill($pid, SIGTERM);
1289

    
1290
		/* wait until the process exits, or timeout and kill it */
1291
		$i = 0;
1292
		while (posix_kill($pid, 0)) {
1293
			usleep(250000);
1294
			if ($i > 10) {
1295
				log_error(sprintf(gettext('OpenVPN ID %1$s PID %2$s still running, killing.'), $mode_id, $pid));
1296
				posix_kill($pid, SIGKILL);
1297
				usleep(500000);
1298
			}
1299
			$i++;
1300
		}
1301
	}
1302

    
1303
	if (isset($settings['disable'])) {
1304
		unlock($lockhandle);
1305
		return;
1306
	}
1307

    
1308
	/* Do not start an instance if we are not CARP master on this vip! */
1309
	if (strstr($settings['interface'], "_vip") && !in_array(get_carp_interface_status($settings['interface']), array("MASTER", ""))) {
1310
		unlock($lockhandle);
1311
		return;
1312
	}
1313

    
1314
	/* Check if client is bound to a gateway group */
1315
	$a_groups = return_gateway_groups_array();
1316
	if (is_array($a_groups[$settings['interface']])) {
1317
		/* the interface is a gateway group. If a vip is defined and its a CARP backup then do not start */
1318
		if (($a_groups[$settings['interface']][0]['vip'] <> "") && (!in_array(get_carp_interface_status($a_groups[$settings['interface']][0]['vip']), array("MASTER", "")))) {
1319
			unlock($lockhandle);
1320
			return;
1321
		}
1322
	}
1323

    
1324
	/* start the new process */
1325
	$fpath = $g['varetc_path']."/openvpn/{$mode_id}.conf";
1326
	openvpn_clear_route($mode, $settings);
1327
	$res = mwexec("/usr/local/sbin/openvpn --config " . escapeshellarg($fpath));
1328
	if ($res == 0) {
1329
		$i = 0;
1330
		$pid = "--";
1331
		while ($i < 3000) {
1332
			if (isvalidpid($pfile)) {
1333
				$pid = rtrim(file_get_contents($pfile));
1334
				break;
1335
			}
1336
			usleep(1000);
1337
			$i++;
1338
		}
1339
		syslog(LOG_INFO, "OpenVPN PID written: {$pid}");
1340
	} else {
1341
		syslog(LOG_ERR, "OpenVPN failed to start");
1342
	}
1343
	if (!platform_booting()) {
1344
		send_event("filter reload");
1345
	}
1346
	unlock($lockhandle);
1347
}
1348

    
1349
function openvpn_delete($mode, $settings) {
1350
	global $g, $config;
1351

    
1352
	$vpnid = $settings['vpnid'];
1353
	$mode_id = $mode.$vpnid;
1354

    
1355
	if ($mode == "server") {
1356
		$devname = "ovpns{$vpnid}";
1357
	} else {
1358
		$devname = "ovpnc{$vpnid}";
1359
	}
1360

    
1361
	/* kill the process if running */
1362
	$pfile = "{$g['varrun_path']}/openvpn_{$mode_id}.pid";
1363
	if (file_exists($pfile)) {
1364

    
1365
		/* read the pid file */
1366
		$pid = trim(file_get_contents($pfile));
1367
		unlink($pfile);
1368

    
1369
		/* send a term signal to the process */
1370
		posix_kill($pid, SIGTERM);
1371
	}
1372

    
1373
	/* destroy the device */
1374
	pfSense_interface_destroy($devname);
1375

    
1376
	/* remove the configuration files */
1377
	@array_map('unlink', glob("{$g['varetc_path']}/openvpn/{$mode_id}.*"));
1378
}
1379

    
1380
function openvpn_resync_csc(& $settings) {
1381
	global $g, $config, $openvpn_tls_server_modes;
1382

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

    
1385
	if (isset($settings['disable'])) {
1386
		openvpn_delete_csc($settings);
1387
		return;
1388
	}
1389
	openvpn_create_dirs();
1390

    
1391
	if (empty($settings['server_list'])) {
1392
		$csc_server_list = array();
1393
	} else {
1394
		$csc_server_list = explode(",", $settings['server_list']);
1395
	}
1396

    
1397
	$conf = '';
1398
	if ($settings['block']) {
1399
		$conf .= "disable\n";
1400
	}
1401

    
1402
	if ($settings['push_reset']) {
1403
		$conf .= "push-reset\n";
1404
	}
1405

    
1406
	if ($settings['local_network']) {
1407
		$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1408
	}
1409
	if ($settings['local_networkv6']) {
1410
		$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1411
	}
1412

    
1413
	// Add a remote network iroute if set
1414
	if (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE) {
1415
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false, true);
1416
	}
1417
	// Add a remote network iroute if set
1418
	if (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE) {
1419
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false, true);
1420
	}
1421

    
1422
	openvpn_add_dhcpopts($settings, $conf);
1423

    
1424
	openvpn_add_custom($settings, $conf);
1425
	/* Loop through servers, find which ones can use this CSC */
1426
	if (is_array($config['openvpn']['openvpn-server'])) {
1427
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1428
			if (isset($serversettings['disable'])) {
1429
				continue;
1430
			}
1431
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1432
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1433
					$csc_path = "{$csc_base_path}/server{$serversettings['vpnid']}/" . basename($settings['common_name']);
1434
					$csc_conf = $conf;
1435

    
1436
					if (!empty($serversettings['tunnel_network']) && !empty($settings['tunnel_network'])) {
1437
						list($ip, $mask) = explode('/', trim($settings['tunnel_network']));
1438
						if (($serversettings['dev_mode'] == 'tap') || ($serversettings['topology'] == "subnet")) {
1439
							$csc_conf .= "ifconfig-push {$ip} " . gen_subnet_mask($mask) . "\n";
1440
						} else {
1441
							/* Because this is being pushed, the order from the client's point of view. */
1442
							$baselong = gen_subnetv4($ip, $mask);
1443
							$serverip = ip_after($baselong, 1);
1444
							$clientip = ip_after($baselong, 2);
1445
							$csc_conf .= "ifconfig-push {$clientip} {$serverip}\n";
1446
						}
1447
					}
1448

    
1449
					if (!empty($serversettings['tunnel_networkv6']) && !empty($settings['tunnel_networkv6'])) {
1450
						list($ipv6, $prefix) = explode('/', trim($serversettings['tunnel_networkv6']));
1451
						list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1452
						$csc_conf .= "ifconfig-ipv6-push {$settings['tunnel_networkv6']} {$ipv6_1}\n";
1453
					}
1454

    
1455
					file_put_contents($csc_path, $csc_conf);
1456
					chown($csc_path, 'nobody');
1457
					chgrp($csc_path, 'nobody');
1458
				}
1459
			}
1460
		}
1461
	}
1462
}
1463

    
1464
function openvpn_resync_csc_all() {
1465
	global $config;
1466
	if (is_array($config['openvpn']['openvpn-csc'])) {
1467
		foreach ($config['openvpn']['openvpn-csc'] as & $settings) {
1468
			openvpn_resync_csc($settings);
1469
		}
1470
	}
1471
}
1472

    
1473
function openvpn_delete_csc(& $settings) {
1474
	global $g, $config, $openvpn_tls_server_modes;
1475
	$csc_base_path = "{$g['varetc_path']}/openvpn-csc";
1476
	if (empty($settings['server_list'])) {
1477
		$csc_server_list = array();
1478
	} else {
1479
		$csc_server_list = explode(",", $settings['server_list']);
1480
	}
1481

    
1482
	/* Loop through servers, find which ones used this CSC */
1483
	if (is_array($config['openvpn']['openvpn-server'])) {
1484
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1485
			if (isset($serversettings['disable'])) {
1486
				continue;
1487
			}
1488
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1489
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1490
					$csc_path = "{$csc_base_path}/server{$serversettings['vpnid']}/" . basename($settings['common_name']);
1491
					unlink_if_exists($csc_path);
1492
				}
1493
			}
1494
		}
1495
	}
1496
}
1497

    
1498
// Resync the configuration and restart the VPN
1499
function openvpn_resync($mode, $settings) {
1500
	openvpn_restart($mode, $settings);
1501
}
1502

    
1503
// Resync and restart all VPNs
1504
function openvpn_resync_all($interface = "") {
1505
	global $g, $config;
1506

    
1507
	openvpn_create_dirs();
1508

    
1509
	if (!is_array($config['openvpn'])) {
1510
		$config['openvpn'] = array();
1511
	}
1512

    
1513
/*
1514
	if (!$config['openvpn']['dh-parameters']) {
1515
		echo "Configuring OpenVPN Parameters ...\n";
1516
		$dh_parameters = openvpn_create_dhparams(1024);
1517
		$dh_parameters = base64_encode($dh_parameters);
1518
		$config['openvpn']['dh-parameters'] = $dh_parameters;
1519
		write_config("OpenVPN DH parameters");
1520
	}
1521

    
1522
	$path_ovdh = $g['varetc_path']."/openvpn/dh-parameters";
1523
	if (!file_exists($path_ovdh)) {
1524
		$dh_parameters = $config['openvpn']['dh-parameters'];
1525
		$dh_parameters = base64_decode($dh_parameters);
1526
		file_put_contents($path_ovdh, $dh_parameters);
1527
	}
1528
*/
1529
	if ($interface <> "") {
1530
		log_error(sprintf(gettext("Resyncing OpenVPN instances for interface %s."), convert_friendly_interface_to_friendly_descr($interface)));
1531
	} else {
1532
		log_error(gettext("Resyncing OpenVPN instances."));
1533
	}
1534

    
1535
	if (is_array($config['openvpn']['openvpn-server'])) {
1536
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1537
			if ($interface <> "" && $interface != $settings['interface']) {
1538
				continue;
1539
			}
1540
			openvpn_resync('server', $settings);
1541
		}
1542
	}
1543

    
1544
	if (is_array($config['openvpn']['openvpn-client'])) {
1545
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1546
			if ($interface <> "" && $interface != $settings['interface']) {
1547
				continue;
1548
			}
1549
			openvpn_resync('client', $settings);
1550
		}
1551
	}
1552

    
1553
	openvpn_resync_csc_all();
1554

    
1555
}
1556

    
1557
// Resync and restart all VPNs using a gateway group.
1558
function openvpn_resync_gwgroup($gwgroupname = "") {
1559
	global $g, $config;
1560

    
1561
	if ($gwgroupname <> "") {
1562
		if (is_array($config['openvpn']['openvpn-server'])) {
1563
			foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1564
				if ($gwgroupname == $settings['interface']) {
1565
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s server %2$s.'), $gwgroupname, $settings["description"]));
1566
					openvpn_resync('server', $settings);
1567
				}
1568
			}
1569
		}
1570

    
1571
		if (is_array($config['openvpn']['openvpn-client'])) {
1572
			foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1573
				if ($gwgroupname == $settings['interface']) {
1574
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s client %2$s.'), $gwgroupname, $settings["description"]));
1575
					openvpn_resync('client', $settings);
1576
				}
1577
			}
1578
		}
1579

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

    
1582
	} else {
1583
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1584
	}
1585
}
1586

    
1587
function openvpn_get_active_servers($type="multipoint") {
1588
	global $config, $g;
1589

    
1590
	$servers = array();
1591
	if (is_array($config['openvpn']['openvpn-server'])) {
1592
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1593
			if (empty($settings) || isset($settings['disable'])) {
1594
				continue;
1595
			}
1596

    
1597
			$prot = $settings['protocol'];
1598
			$port = $settings['local_port'];
1599

    
1600
			$server = array();
1601
			$server['port'] = ($settings['local_port']) ? $settings['local_port'] : 1194;
1602
			$server['mode'] = $settings['mode'];
1603
			if ($settings['description']) {
1604
				$server['name'] = "{$settings['description']} {$prot}:{$port}";
1605
			} else {
1606
				$server['name'] = "Server {$prot}:{$port}";
1607
			}
1608
			$server['conns'] = array();
1609
			$server['vpnid'] = $settings['vpnid'];
1610
			$server['mgmt'] = "server{$server['vpnid']}";
1611
			$socket = "unix://{$g['varetc_path']}/openvpn/{$server['mgmt']}.sock";
1612
			list($tn, $sm) = explode('/', trim($settings['tunnel_network']));
1613

    
1614
			if ((($server['mode'] == "p2p_shared_key") || ($sm >= 30)) && ($type == "p2p")) {
1615
				$servers[] = openvpn_get_client_status($server, $socket);
1616
			} elseif (($server['mode'] != "p2p_shared_key") && ($type == "multipoint") && ($sm < 30)) {
1617
				$servers[] = openvpn_get_server_status($server, $socket);
1618
			}
1619
		}
1620
	}
1621
	return $servers;
1622
}
1623

    
1624
function openvpn_get_server_status($server, $socket) {
1625
	$errval = null;
1626
	$errstr = null;
1627
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1628
	if ($fp) {
1629
		stream_set_timeout($fp, 1);
1630

    
1631
		/* send our status request */
1632
		fputs($fp, "status 2\n");
1633

    
1634
		/* recv all response lines */
1635
		while (!feof($fp)) {
1636

    
1637
			/* read the next line */
1638
			$line = fgets($fp, 1024);
1639

    
1640
			$info = stream_get_meta_data($fp);
1641
			if ($info['timed_out']) {
1642
				break;
1643
			}
1644

    
1645
			/* parse header list line */
1646
			if (strstr($line, "HEADER")) {
1647
				continue;
1648
			}
1649

    
1650
			/* parse end of output line */
1651
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1652
				break;
1653
			}
1654

    
1655
			/* parse client list line */
1656
			if (strstr($line, "CLIENT_LIST")) {
1657
				$list = explode(",", $line);
1658
				$conn = array();
1659
				$conn['common_name'] = $list[1];
1660
				$conn['remote_host'] = $list[2];
1661
				$conn['virtual_addr'] = $list[3];
1662
				$conn['virtual_addr6'] = $list[4];
1663
				$conn['bytes_recv'] = $list[5];
1664
				$conn['bytes_sent'] = $list[6];
1665
				$conn['connect_time'] = $list[7];
1666
				$conn['connect_time_unix'] = $list[8];
1667
				$conn['user_name'] = $list[9];
1668
				$conn['client_id'] = $list[10];
1669
				$conn['peer_id'] = $list[11];
1670
				$server['conns'][] = $conn;
1671
			}
1672
			/* parse routing table lines */
1673
			if (strstr($line, "ROUTING_TABLE")) {
1674
				$list = explode(",", $line);
1675
				$conn = array();
1676
				$conn['virtual_addr'] = $list[1];
1677
				$conn['common_name'] = $list[2];
1678
				$conn['remote_host'] = $list[3];
1679
				$conn['last_time'] = $list[4];
1680
				$server['routes'][] = $conn;
1681
			}
1682
		}
1683

    
1684
		/* cleanup */
1685
		fclose($fp);
1686
	} else {
1687
		$conn = array();
1688
		$conn['common_name'] = "[error]";
1689
		$conn['remote_host'] = gettext("Unable to contact daemon");
1690
		$conn['virtual_addr'] = gettext("Service not running?");
1691
		$conn['bytes_recv'] = 0;
1692
		$conn['bytes_sent'] = 0;
1693
		$conn['connect_time'] = 0;
1694
		$server['conns'][] = $conn;
1695
	}
1696
	return $server;
1697
}
1698

    
1699
function openvpn_get_active_clients() {
1700
	global $config, $g;
1701

    
1702
	$clients = array();
1703
	if (is_array($config['openvpn']['openvpn-client'])) {
1704
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1705

    
1706
			if (empty($settings) || isset($settings['disable'])) {
1707
				continue;
1708
			}
1709

    
1710
			$prot = $settings['protocol'];
1711
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
1712

    
1713
			$client = array();
1714
			$client['port'] = $settings['local_port'];
1715
			if ($settings['description']) {
1716
				$client['name'] = "{$settings['description']} {$prot}{$port}";
1717
			} else {
1718
				$client['name'] = "Client {$prot}{$port}";
1719
			}
1720

    
1721
			$client['vpnid'] = $settings['vpnid'];
1722
			$client['mgmt'] = "client{$client['vpnid']}";
1723
			$socket = "unix://{$g['varetc_path']}/openvpn/{$client['mgmt']}.sock";
1724
			$client['status']="down";
1725

    
1726
			$clients[] = openvpn_get_client_status($client, $socket);
1727
		}
1728
	}
1729
	return $clients;
1730
}
1731

    
1732
function openvpn_get_client_status($client, $socket) {
1733
	$errval = null;
1734
	$errstr = null;
1735
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1736
	if ($fp) {
1737
		stream_set_timeout($fp, 1);
1738
		/* send our status request */
1739
		fputs($fp, "state 1\n");
1740

    
1741
		/* recv all response lines */
1742
		while (!feof($fp)) {
1743
			/* read the next line */
1744
			$line = fgets($fp, 1024);
1745

    
1746
			$info = stream_get_meta_data($fp);
1747
			if ($info['timed_out']) {
1748
				break;
1749
			}
1750

    
1751
			/* Get the client state */
1752
			if (strstr($line, "CONNECTED")) {
1753
				$client['status'] = "up";
1754
				$list = explode(",", $line);
1755

    
1756
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1757
				$client['virtual_addr'] = $list[3];
1758
				$client['remote_host'] = $list[4];
1759
				$client['remote_port'] = $list[5];
1760
				$client['local_host'] = $list[6];
1761
				$client['local_port'] = $list[7];
1762
				$client['virtual_addr6'] = $list[8];
1763
			}
1764
			if (strstr($line, "CONNECTING")) {
1765
				$client['status'] = "connecting";
1766
			}
1767
			if (strstr($line, "ASSIGN_IP")) {
1768
				$client['status'] = "waiting";
1769
				$list = explode(",", $line);
1770

    
1771
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1772
				$client['virtual_addr'] = $list[3];
1773
			}
1774
			if (strstr($line, "RECONNECTING")) {
1775
				$client['status'] = "reconnecting";
1776
				$list = explode(",", $line);
1777

    
1778
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1779
				$client['status'] .= "; " . $list[2];
1780
			}
1781
			/* parse end of output line */
1782
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1783
				break;
1784
			}
1785
		}
1786

    
1787
		/* If up, get read/write stats */
1788
		if (strcmp($client['status'], "up") == 0) {
1789
			fputs($fp, "status 2\n");
1790
			/* recv all response lines */
1791
			while (!feof($fp)) {
1792
				/* read the next line */
1793
				$line = fgets($fp, 1024);
1794

    
1795
				$info = stream_get_meta_data($fp);
1796
				if ($info['timed_out']) {
1797
					break;
1798
				}
1799

    
1800
				if (strstr($line, "TCP/UDP read bytes")) {
1801
					$list = explode(",", $line);
1802
					$client['bytes_recv'] = $list[1];
1803
				}
1804

    
1805
				if (strstr($line, "TCP/UDP write bytes")) {
1806
					$list = explode(",", $line);
1807
					$client['bytes_sent'] = $list[1];
1808
				}
1809

    
1810
				/* parse end of output line */
1811
				if (strstr($line, "END")) {
1812
					break;
1813
				}
1814
			}
1815
		}
1816

    
1817
		fclose($fp);
1818

    
1819
	} else {
1820
		$client['remote_host'] = gettext("Unable to contact daemon");
1821
		$client['virtual_addr'] = gettext("Service not running?");
1822
		$client['bytes_recv'] = 0;
1823
		$client['bytes_sent'] = 0;
1824
		$client['connect_time'] = 0;
1825
	}
1826
	return $client;
1827
}
1828

    
1829
function openvpn_kill_client($port, $remipp) {
1830
	global $g;
1831

    
1832
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
1833
	$tcpsrv = "unix://{$g['varetc_path']}/openvpn/{$port}.sock";
1834
	$errval = null;
1835
	$errstr = null;
1836

    
1837
	/* open a tcp connection to the management port of each server */
1838
	$fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
1839
	$killed = -1;
1840
	if ($fp) {
1841
		stream_set_timeout($fp, 1);
1842
		fputs($fp, "kill {$remipp}\n");
1843
		while (!feof($fp)) {
1844
			$line = fgets($fp, 1024);
1845

    
1846
			$info = stream_get_meta_data($fp);
1847
			if ($info['timed_out']) {
1848
				break;
1849
			}
1850

    
1851
			/* parse header list line */
1852
			if (strpos($line, "INFO:") !== false) {
1853
				continue;
1854
			}
1855
			if (strpos($line, "SUCCESS") !== false) {
1856
				$killed = 0;
1857
			}
1858
			break;
1859
		}
1860
		fclose($fp);
1861
	}
1862
	return $killed;
1863
}
1864

    
1865
function openvpn_refresh_crls() {
1866
	global $g, $config;
1867

    
1868
	openvpn_create_dirs();
1869

    
1870
	if (is_array($config['openvpn']['openvpn-server'])) {
1871
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
1872
			if (empty($settings)) {
1873
				continue;
1874
			}
1875
			if (isset($settings['disable'])) {
1876
				continue;
1877
			}
1878
			// Write the settings for the keys
1879
			switch ($settings['mode']) {
1880
				case 'p2p_tls':
1881
				case 'server_tls':
1882
				case 'server_tls_user':
1883
				case 'server_user':
1884
					if (!empty($settings['crlref'])) {
1885
						$crl = lookup_crl($settings['crlref']);
1886
						crl_update($crl);
1887
						$fpath = $g['varetc_path']."/openvpn/server{$settings['vpnid']}.crl-verify";
1888
						file_put_contents($fpath, base64_decode($crl['text']));
1889
						@chmod($fpath, 0644);
1890
					}
1891
					break;
1892
			}
1893
		}
1894
	}
1895
}
1896

    
1897
function openvpn_create_dirs() {
1898
	global $g, $config, $openvpn_tls_server_modes;
1899
	if (!is_dir("{$g['varetc_path']}/openvpn")) {
1900
		safe_mkdir("{$g['varetc_path']}/openvpn", 0750);
1901
	}
1902
	if (!is_dir("{$g['varetc_path']}/openvpn-csc")) {
1903
		safe_mkdir("{$g['varetc_path']}/openvpn-csc", 0750);
1904
	}
1905

    
1906
	/* Check for enabled servers and create server-specific CSC dirs */
1907
	if (is_array($config['openvpn']['openvpn-server'])) {
1908
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
1909
			if (isset($settings['disable'])) {
1910
				continue;
1911
			}
1912
			if (in_array($settings['mode'], $openvpn_tls_server_modes)) {
1913
				if ($settings['vpnid']) {
1914
					safe_mkdir("{$g['varetc_path']}/openvpn-csc/server{$settings['vpnid']}");
1915
				}
1916
			}
1917
		}
1918
	}
1919
}
1920

    
1921
function openvpn_get_interface_ip($ip, $cidr) {
1922
	$subnet = gen_subnetv4($ip, $cidr);
1923
	$ip1 = ip_after($subnet);
1924
	$ip2 = ip_after($ip1);
1925
	return array($ip1, $ip2);
1926
}
1927

    
1928
function openvpn_get_interface_ipv6($ipv6, $prefix) {
1929
	$basev6 = gen_subnetv6($ipv6, $prefix);
1930
	// Is there a better way to do this math?
1931
	$ipv6_arr = explode(':', $basev6);
1932
	$last = hexdec(array_pop($ipv6_arr));
1933
	$ipv6_1 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 1));
1934
	$ipv6_2 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 2));
1935
	return array($ipv6_1, $ipv6_2);
1936
}
1937

    
1938
function openvpn_clear_route($mode, $settings) {
1939
	if (empty($settings['tunnel_network'])) {
1940
		return;
1941
	}
1942
	list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
1943
	$mask = gen_subnet_mask($cidr);
1944
	$clear_route = false;
1945

    
1946
	switch ($settings['mode']) {
1947
		case 'shared_key':
1948
			$clear_route = true;
1949
			break;
1950
		case 'p2p_tls':
1951
		case 'p2p_shared_key':
1952
			if ($cidr == 30) {
1953
				$clear_route = true;
1954
			}
1955
			break;
1956
	}
1957

    
1958
	if ($clear_route && !empty($ip) && !empty($mask)) {
1959
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1960
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
1961
		/* XXX: Family for route? */
1962
		mwexec("/sbin/route -q delete {$ip_to_clear}");
1963
	}
1964
}
1965

    
1966
function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) {
1967
	$routes = "";
1968
	if (empty($value)) {
1969
		return "";
1970
	}
1971
	$networks = explode(',', $value);
1972

    
1973
	foreach ($networks as $network) {
1974
		if ($ipproto == "ipv4") {
1975
			$route = openvpn_gen_route_ipv4($network, $iroute);
1976
		} else {
1977
			$route = openvpn_gen_route_ipv6($network, $iroute);
1978
		}
1979

    
1980
		if ($push) {
1981
			$routes .= "push \"{$route}\"\n";
1982
		} else {
1983
			$routes .= "{$route}\n";
1984
		}
1985
	}
1986
	return $routes;
1987
}
1988

    
1989
function openvpn_gen_route_ipv4($network, $iroute = false) {
1990
	$i = ($iroute) ? "i" : "";
1991
	list($ip, $mask) = explode('/', trim($network));
1992
	$mask = gen_subnet_mask($mask);
1993
	return "{$i}route $ip $mask";
1994
}
1995

    
1996
function openvpn_gen_route_ipv6($network, $iroute = false) {
1997
	$i = ($iroute) ? "i" : "";
1998
	list($ipv6, $prefix) = explode('/', trim($network));
1999
	if (empty($prefix) && !is_numeric($prefix)) {
2000
		$prefix = "128";
2001
	}
2002
	return "{$i}route-ipv6 ${ipv6}/${prefix}";
2003
}
2004

    
2005
function openvpn_get_settings($mode, $vpnid) {
2006
	global $config;
2007

    
2008
	if (is_array($config['openvpn']['openvpn-server'])) {
2009
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
2010
			if (isset($settings['disable'])) {
2011
				continue;
2012
			}
2013

    
2014
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2015
				return $settings;
2016
			}
2017
		}
2018
	}
2019

    
2020
	if (is_array($config['openvpn']['openvpn-client'])) {
2021
		foreach ($config['openvpn']['openvpn-client'] as $settings) {
2022
			if (isset($settings['disable'])) {
2023
				continue;
2024
			}
2025

    
2026
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2027
				return $settings;
2028
			}
2029
		}
2030
	}
2031

    
2032
	return array();
2033
}
2034

    
2035
function openvpn_restart_by_vpnid($mode, $vpnid) {
2036
	$settings = openvpn_get_settings($mode, $vpnid);
2037
	openvpn_restart($mode, $settings);
2038
}
2039

    
2040
?>
(30-30/54)