Project

General

Profile

Download (51.3 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("UDP", "UDP6", "TCP", "TCP6");
37

    
38
global $openvpn_dev_mode;
39
$openvpn_dev_mode = array("tun", "tap");
40

    
41
global $openvpn_verbosity_level;
42
$openvpn_verbosity_level = array(
43
	0 =>	gettext("none"),
44
	1 =>	gettext("default"),
45
	2 =>	"2",
46
	3 =>	gettext("3 (recommended)"),
47
	4 =>	"4",
48
	5 => 	"5",
49
	6 => 	"6",
50
	7 => 	"7",
51
	8 => 	"8",
52
	9 => 	"9",
53
	10 => 	"10",
54
	11 => 	"11"
55
);
56

    
57
/*
58
 * The User Auth mode below is disabled because
59
 * OpenVPN erroneously requires that we provide
60
 * a CA configuration parameter. In this mode,
61
 * clients don't send a certificate so there is
62
 * no need for a CA. If we require that admins
63
 * provide one in the pfSense UI due to a bogus
64
 * requirement imposed by OpenVPN, it could be
65
 * considered very confusing ( I know I was ).
66
 *
67
 * -mgrooms
68
 */
69

    
70
global $openvpn_dh_lengths;
71
$openvpn_dh_lengths = array(
72
	1024, 2048, 3072, 4096, 7680, 8192, 15360, 16384
73
);
74

    
75
global $openvpn_cert_depths;
76
$openvpn_cert_depths = array(
77
	1 => gettext("One (Client+Server)"),
78
	2 => gettext("Two (Client+Intermediate+Server)"),
79
	3 => gettext("Three (Client+2xIntermediate+Server)"),
80
	4 => gettext("Four (Client+3xIntermediate+Server)"),
81
	5 => gettext("Five (Client+4xIntermediate+Server)")
82
);
83

    
84
global $openvpn_server_modes;
85
$openvpn_server_modes = array(
86
	'p2p_tls' => gettext("Peer to Peer ( SSL/TLS )"),
87
	'p2p_shared_key' => gettext("Peer to Peer ( Shared Key )"),
88
	'server_tls' => gettext("Remote Access ( SSL/TLS )"),
89
	'server_user' => gettext("Remote Access ( User Auth )"),
90
	'server_tls_user' => gettext("Remote Access ( SSL/TLS + User Auth )"));
91

    
92
global $openvpn_tls_server_modes;
93
$openvpn_tls_server_modes = array('p2p_tls', 'server_tls', 'server_user', 'server_tls_user');
94

    
95
global $openvpn_client_modes;
96
$openvpn_client_modes = array(
97
	'p2p_tls' => gettext("Peer to Peer ( SSL/TLS )"),
98
	'p2p_shared_key' => gettext("Peer to Peer ( Shared Key )"));
99

    
100
global $openvpn_compression_modes;
101
$openvpn_compression_modes = array(
102
	'' => gettext("No Preference"),
103
	'noadapt' => gettext("No Preference and Adaptive Compression Disabled"),
104
	'no' => gettext("Disabled - No Compression"),
105
	'adaptive' => gettext("Enabled with Adaptive Compression"),
106
	'yes' => gettext("Enabled without Adaptive Compression"));
107

    
108
global $openvpn_topologies;
109
$openvpn_topologies = array(
110
	'subnet' => gettext("Subnet -- One IP address per client in a common subnet"),
111
	'net30' => gettext("net30 -- Isolated /30 network per client")
112
//	'p2p => gettext("Peer to Peer -- One IP address per client peer-to-peer style. Does not work on Windows.")
113
);
114

    
115
function openvpn_build_mode_list() {
116
	global $openvpn_server_modes;
117

    
118
	$list = array();
119

    
120
	foreach ($openvpn_server_modes as $name => $desc) {
121
		$list[$name] = $desc;
122
	}
123

    
124
	return($list);
125
}
126

    
127
function openvpn_build_if_list() {
128
	$list = array();
129

    
130
	$interfaces = get_configured_interface_with_descr();
131
	$viplist = get_configured_vip_list();
132
	foreach ($viplist as $vip => $address) {
133
		$interfaces[$vip.'|'.$address] = $address;
134
		if (get_vip_descr($address)) {
135
			$interfaces[$vip.'|'.$address] .= " (";
136
			$interfaces[$vip.'|'.$address] .= get_vip_descr($address);
137
			$interfaces[$vip.'|'.$address] .= ")";
138
		}
139
	}
140

    
141
	$grouplist = return_gateway_groups_array();
142
	foreach ($grouplist as $name => $group) {
143
		if ($group[0]['vip'] != "") {
144
			$vipif = $group[0]['vip'];
145
		} else {
146
			$vipif = $group[0]['int'];
147
		}
148

    
149
		$interfaces[$name] = "GW Group {$name}";
150
	}
151

    
152
	$interfaces['lo0'] = "Localhost";
153
	$interfaces['any'] = "any";
154

    
155
	foreach ($interfaces as $iface => $ifacename) {
156
	   $list[$iface] = $ifacename;
157
	}
158

    
159
	return($list);
160
}
161

    
162
function openvpn_build_crl_list() {
163
	global $a_crl;
164

    
165
	$list = array('' => 'None');
166

    
167
	foreach ($a_crl as $crl) {
168
		$caname = "";
169
		$ca = lookup_ca($crl['caref']);
170

    
171
		if ($ca) {
172
			$caname = " (CA: {$ca['descr']})";
173
		}
174

    
175
		$list[$crl['refid']] = $crl['descr'] . $caname;
176
	}
177

    
178
	return($list);
179
}
180

    
181
function openvpn_build_cert_list($include_none = false, $prioritize_server_certs = false) {
182
	global $a_cert;
183

    
184
	if ($include_none) {
185
		$list = array('' => gettext('None (Username and/or Password required)'));
186
	} else {
187
		$list = array();
188
	}
189

    
190
	$non_server_list = array();
191

    
192
	if ($prioritize_server_certs) {
193
		$list[' '] = gettext("===== Server Certificates =====");
194
		$non_server_list['  '] = gettext("===== Non-Server Certificates =====");
195
	}
196

    
197
	foreach ($a_cert as $cert) {
198
		$properties = array();
199
		$propstr = "";
200
		$ca = lookup_ca($cert['caref']);
201
		$purpose = cert_get_purpose($cert['crt'], true);
202

    
203
		if ($purpose['server'] == "Yes") {
204
			$properties[] = gettext("Server: Yes");
205
		} elseif ($prioritize_server_certs) {
206
			$properties[] = gettext("Server: NO");
207
		}
208
		if ($ca) {
209
			$properties[] = sprintf(gettext("CA: %s"), $ca['descr']);
210
		}
211
		if (cert_in_use($cert['refid'])) {
212
			$properties[] = gettext("In Use");
213
		}
214
		if (is_cert_revoked($cert)) {
215
			$properties[] = gettext("Revoked");
216
		}
217

    
218
		if (!empty($properties)) {
219
			$propstr = " (" . implode(", ", $properties) . ")";
220
		}
221

    
222
		if ($prioritize_server_certs) {
223
			if ($purpose['server'] == "Yes") {
224
				$list[$cert['refid']] = $cert['descr'] . $propstr;
225
			} else {
226
				$non_server_list[$cert['refid']] = $cert['descr'] . $propstr;
227
			}
228
		} else {
229
			$list[$cert['refid']] = $cert['descr'] . $propstr;
230
		}
231
	}
232

    
233
	return(array('server' => $list, 'non-server' => $non_server_list));
234
}
235

    
236
function openvpn_build_bridge_list() {
237
	$list = array();
238

    
239
	$serverbridge_interface['none'] = "none";
240
	$serverbridge_interface = array_merge($serverbridge_interface, get_configured_interface_with_descr());
241
	$viplist = get_configured_vip_list();
242

    
243
	foreach ($viplist as $vip => $address) {
244
		$serverbridge_interface[$vip.'|'.$address] = $address;
245
		if (get_vip_descr($address)) {
246
			$serverbridge_interface[$vip.'|'.$address] .= " (". get_vip_descr($address) .")";
247
		}
248
	}
249

    
250
	foreach ($serverbridge_interface as $iface => $ifacename) {
251
		$list[$iface] = htmlspecialchars($ifacename);
252
	}
253

    
254
	return($list);
255
}
256

    
257
function openvpn_create_key() {
258

    
259
	$fp = popen("/usr/local/sbin/openvpn --genkey --secret /dev/stdout 2>/dev/null", "r");
260
	if (!$fp) {
261
		return false;
262
	}
263

    
264
	$rslt = stream_get_contents($fp);
265
	pclose($fp);
266

    
267
	return $rslt;
268
}
269

    
270
function openvpn_create_dhparams($bits) {
271

    
272
	$fp = popen("/usr/bin/openssl dhparam {$bits} 2>/dev/null", "r");
273
	if (!$fp) {
274
		return false;
275
	}
276

    
277
	$rslt = stream_get_contents($fp);
278
	pclose($fp);
279

    
280
	return $rslt;
281
}
282

    
283
function openvpn_vpnid_used($vpnid) {
284
	global $config;
285

    
286
	if (is_array($config['openvpn']['openvpn-server'])) {
287
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
288
			if ($vpnid == $settings['vpnid']) {
289
				return true;
290
			}
291
		}
292
	}
293

    
294
	if (is_array($config['openvpn']['openvpn-client'])) {
295
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
296
			if ($vpnid == $settings['vpnid']) {
297
				return true;
298
			}
299
		}
300
	}
301

    
302
	return false;
303
}
304

    
305
function openvpn_vpnid_next() {
306

    
307
	$vpnid = 1;
308
	while (openvpn_vpnid_used($vpnid)) {
309
		$vpnid++;
310
	}
311

    
312
	return $vpnid;
313
}
314

    
315
function openvpn_port_used($prot, $interface, $port, $curvpnid = 0) {
316
	global $config;
317

    
318
	if (is_array($config['openvpn']['openvpn-server'])) {
319
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
320
			if (isset($settings['disable'])) {
321
				continue;
322
			}
323

    
324
			if ($curvpnid != 0 && $curvpnid == $settings['vpnid']) {
325
				continue;
326
			}
327

    
328
			if ($port == $settings['local_port'] && $prot == $settings['protocol'] &&
329
			    ($interface == $settings['interface'] || $interface == "any" || $settings['interface'] == "any")) {
330
				return $settings['vpnid'];
331
			}
332
		}
333
	}
334

    
335
	if (is_array($config['openvpn']['openvpn-client'])) {
336
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
337
			if (isset($settings['disable'])) {
338
				continue;
339
			}
340

    
341
			if ($curvpnid != 0 && $curvpnid == $settings['vpnid']) {
342
				continue;
343
			}
344

    
345
			if ($port == $settings['local_port'] && $prot == $settings['protocol'] &&
346
			    ($interface == $settings['interface'] || $interface == "any" || $settings['interface'] == "any")) {
347
				return $settings['vpnid'];
348
			}
349
		}
350
	}
351

    
352
	return 0;
353
}
354

    
355
function openvpn_port_next($prot, $interface = "wan") {
356

    
357
	$port = 1194;
358
	while (openvpn_port_used($prot, $interface, $port)) {
359
		$port++;
360
	}
361
	while (openvpn_port_used($prot, "any", $port)) {
362
		$port++;
363
	}
364

    
365
	return $port;
366
}
367

    
368
function openvpn_get_cipherlist() {
369

    
370
	$ciphers = array();
371
	$cipher_out = shell_exec('/usr/local/sbin/openvpn --show-ciphers | /usr/bin/grep \'(.*key\' | sed \'s/, TLS client\/server mode only//\'');
372
	$cipher_lines = explode("\n", trim($cipher_out));
373
	sort($cipher_lines);
374
	foreach ($cipher_lines as $line) {
375
		$words = explode(' ', $line, 2);
376
		$ciphers[$words[0]] = "{$words[0]} {$words[1]}";
377
	}
378
	$ciphers["none"] = gettext("None (No Encryption)");
379
	return $ciphers;
380
}
381

    
382
function openvpn_get_digestlist() {
383

    
384
	$digests = array();
385
	$digest_out = shell_exec('/usr/local/sbin/openvpn --show-digests | /usr/bin/grep "digest size" | /usr/bin/awk \'{print $1, "(" $2 "-" $3 ")";}\'');
386
	$digest_lines = explode("\n", trim($digest_out));
387
	sort($digest_lines);
388
	foreach ($digest_lines as $line) {
389
		$words = explode(' ', $line);
390
		$digests[$words[0]] = "{$words[0]} {$words[1]}";
391
	}
392
	$digests["none"] = gettext("None (No Authentication)");
393
	return $digests;
394
}
395

    
396
function openvpn_get_engines() {
397
	$openssl_engines = array('none' => gettext('No Hardware Crypto Acceleration'));
398
	exec("/usr/bin/openssl engine -t -c", $openssl_engine_output);
399
	$openssl_engine_output = implode("\n", $openssl_engine_output);
400
	$openssl_engine_output = preg_replace("/\\n\\s+/", "|", $openssl_engine_output);
401
	$openssl_engine_output = explode("\n", $openssl_engine_output);
402

    
403
	foreach ($openssl_engine_output as $oeo) {
404
		$keep = true;
405
		$details = explode("|", $oeo);
406
		$engine = array_shift($details);
407
		$linematch = array();
408
		preg_match("/\((.*)\)\s(.*)/", $engine, $linematch);
409
		foreach ($details as $dt) {
410
			if (strpos($dt, "unavailable") !== FALSE) {
411
				$keep = false;
412
			}
413
			if (strpos($dt, "available") !== FALSE) {
414
				continue;
415
			}
416
			if (strpos($dt, "[") !== FALSE) {
417
				$ciphers = trim($dt, "[]");
418
			}
419
		}
420
		if (!empty($ciphers)) {
421
			$ciphers = " - " . $ciphers;
422
		}
423
		if (strlen($ciphers) > 60) {
424
			$ciphers = substr($ciphers, 0, 60) . " ... ";
425
		}
426
		if ($keep) {
427
			$openssl_engines[$linematch[1]] = $linematch[2] . $ciphers;
428
		}
429
	}
430
	return $openssl_engines;
431
}
432

    
433
function openvpn_validate_engine($engine) {
434
	$engines = openvpn_get_engines();
435
	return array_key_exists($engine, $engines);
436
}
437

    
438
function openvpn_validate_host($value, $name) {
439
	$value = trim($value);
440
	if (empty($value) || (!is_domain($value) && !is_ipaddr($value))) {
441
		return sprintf(gettext("The field '%s' must contain a valid IP address or domain name."), $name);
442
	}
443
	return false;
444
}
445

    
446
function openvpn_validate_port($value, $name) {
447
	$value = trim($value);
448
	if (empty($value) || !is_numeric($value) || $value < 0 || ($value > 65535)) {
449
		return sprintf(gettext("The field '%s' must contain a valid port, ranging from 0 to 65535."), $name);
450
	}
451
	return false;
452
}
453

    
454
function openvpn_validate_cidr($value, $name, $multiple = false, $ipproto = "ipv4") {
455
	$value = trim($value);
456
	$error = false;
457
	if (empty($value)) {
458
		return false;
459
	}
460
	$networks = explode(',', $value);
461

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

    
466
	foreach ($networks as $network) {
467
		if ($ipproto == "ipv4") {
468
			$error = !openvpn_validate_cidr_ipv4($network);
469
		} else {
470
			$error = !openvpn_validate_cidr_ipv6($network);
471
		}
472
		if ($error) {
473
			break;
474
		}
475
	}
476

    
477
	if ($error) {
478
		return sprintf(gettext("The field '%1\$s' must contain only valid %2\$s CIDR range(s) separated by commas."), $name, $ipproto);
479
	} else {
480
		return false;
481
	}
482
}
483

    
484
function openvpn_validate_cidr_ipv4($value) {
485
	$value = trim($value);
486
	if (!empty($value)) {
487
		list($ip, $mask) = explode('/', $value);
488
		if (!is_ipaddrv4($ip) or !is_numeric($mask) or ($mask > 32) or ($mask < 0)) {
489
			return false;
490
		}
491
	}
492
	return true;
493
}
494

    
495
function openvpn_validate_cidr_ipv6($value) {
496
	$value = trim($value);
497
	if (!empty($value)) {
498
		list($ipv6, $prefix) = explode('/', $value);
499
		if (empty($prefix)) {
500
			$prefix = "128";
501
		}
502
		if (!is_ipaddrv6($ipv6) or !is_numeric($prefix) or ($prefix > 128) or ($prefix < 0)) {
503
			return false;
504
		}
505
	}
506
	return true;
507
}
508

    
509
function openvpn_add_dhcpopts(& $settings, & $conf) {
510

    
511
	if (!empty($settings['dns_domain'])) {
512
		$conf .= "push \"dhcp-option DOMAIN {$settings['dns_domain']}\"\n";
513
	}
514

    
515
	if (!empty($settings['dns_server1'])) {
516
		$conf .= "push \"dhcp-option DNS {$settings['dns_server1']}\"\n";
517
	}
518
	if (!empty($settings['dns_server2'])) {
519
		$conf .= "push \"dhcp-option DNS {$settings['dns_server2']}\"\n";
520
	}
521
	if (!empty($settings['dns_server3'])) {
522
		$conf .= "push \"dhcp-option DNS {$settings['dns_server3']}\"\n";
523
	}
524
	if (!empty($settings['dns_server4'])) {
525
		$conf .= "push \"dhcp-option DNS {$settings['dns_server4']}\"\n";
526
	}
527

    
528
	if (!empty($settings['push_blockoutsidedns'])) {
529
		$conf .= "push \"block-outside-dns\"\n";
530
	}
531
	if (!empty($settings['push_register_dns'])) {
532
		$conf .= "push \"register-dns\"\n";
533
	}
534

    
535
	if (!empty($settings['ntp_server1'])) {
536
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server1']}\"\n";
537
	}
538
	if (!empty($settings['ntp_server2'])) {
539
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server2']}\"\n";
540
	}
541

    
542
	if ($settings['netbios_enable']) {
543

    
544
		if (!empty($settings['dhcp_nbttype']) && ($settings['dhcp_nbttype'] != 0)) {
545
			$conf .= "push \"dhcp-option NBT {$settings['dhcp_nbttype']}\"\n";
546
		}
547
		if (!empty($settings['dhcp_nbtscope'])) {
548
			$conf .= "push \"dhcp-option NBS {$settings['dhcp_nbtscope']}\"\n";
549
		}
550

    
551
		if (!empty($settings['wins_server1'])) {
552
			$conf .= "push \"dhcp-option WINS {$settings['wins_server1']}\"\n";
553
		}
554
		if (!empty($settings['wins_server2'])) {
555
			$conf .= "push \"dhcp-option WINS {$settings['wins_server2']}\"\n";
556
		}
557

    
558
		if (!empty($settings['nbdd_server1'])) {
559
			$conf .= "push \"dhcp-option NBDD {$settings['nbdd_server1']}\"\n";
560
		}
561
	}
562

    
563
	if ($settings['gwredir']) {
564
		$conf .= "push \"redirect-gateway def1\"\n";
565
	}
566
}
567

    
568
function openvpn_add_custom(& $settings, & $conf) {
569

    
570
	if ($settings['custom_options']) {
571

    
572
		$options = explode(';', $settings['custom_options']);
573

    
574
		if (is_array($options)) {
575
			foreach ($options as $option) {
576
				$conf .= "$option\n";
577
			}
578
		} else {
579
			$conf .= "{$settings['custom_options']}\n";
580
		}
581
	}
582
}
583

    
584
function openvpn_add_keyfile(& $data, & $conf, $mode_id, $directive, $opt = "") {
585
	global $g;
586

    
587
	$fpath = $g['varetc_path']."/openvpn/{$mode_id}.{$directive}";
588
	openvpn_create_dirs();
589
	file_put_contents($fpath, base64_decode($data));
590
	//chown($fpath, 'nobody');
591
	//chgrp($fpath, 'nobody');
592
	@chmod($fpath, 0600);
593

    
594
	$conf .= "{$directive} {$fpath} {$opt}\n";
595
}
596

    
597
function openvpn_reconfigure($mode, $settings) {
598
	global $g, $config, $openvpn_tls_server_modes;
599

    
600
	if (empty($settings)) {
601
		return;
602
	}
603
	if (isset($settings['disable'])) {
604
		return;
605
	}
606
	openvpn_create_dirs();
607
	/*
608
	 * NOTE: Deleting tap devices causes spontaneous reboots. Instead,
609
	 * we use a vpnid number which is allocated for a particular client
610
	 * or server configuration. ( see openvpn_vpnid_next() )
611
	 */
612

    
613
	$vpnid = $settings['vpnid'];
614
	$mode_id = $mode.$vpnid;
615

    
616
	if (isset($settings['dev_mode'])) {
617
		$tunname = "{$settings['dev_mode']}{$vpnid}";
618
	} else {
619
		/* defaults to tun */
620
		$tunname = "tun{$vpnid}";
621
		$settings['dev_mode'] = "tun";
622
	}
623

    
624
	if ($mode == "server") {
625
		$devname = "ovpns{$vpnid}";
626
	} else {
627
		$devname = "ovpnc{$vpnid}";
628
	}
629

    
630
	/* is our device already configured */
631
	if (!does_interface_exist($devname)) {
632

    
633
		/* create the tap device if required */
634
		if (!file_exists("/dev/{$tunname}")) {
635
			exec("/sbin/ifconfig " . escapeshellarg($tunname) . " create");
636
		}
637

    
638
		/* rename the device */
639
		mwexec("/sbin/ifconfig " . escapeshellarg($tunname) . " name " . escapeshellarg($devname));
640

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

    
644
		$ifname = convert_real_interface_to_friendly_interface_name($devname);
645
		$grouptmp = link_interface_to_group($ifname);
646
		if (!empty($grouptmp)) {
647
			array_walk($grouptmp, 'interface_group_add_member');
648
		}
649
		unset($grouptmp, $ifname);
650
	}
651

    
652
	$pfile = $g['varrun_path'] . "/openvpn_{$mode_id}.pid";
653
	$proto = strtolower($settings['protocol']);
654
	if (substr($settings['protocol'], 0, 3) == "TCP") {
655
			$proto = "{$proto}-{$mode}";
656
	}
657
	$dev_mode = $settings['dev_mode'];
658
	$cipher = $settings['crypto'];
659
	// OpenVPN defaults to SHA1, so use it when unset to maintain compatibility.
660
	$digest = !empty($settings['digest']) ? $settings['digest'] : "SHA1";
661

    
662
	$interface = get_failover_interface($settings['interface']);
663
	// The IP address in the settings can be an IPv4 or IPv6 address associated with the interface
664
	$ipaddr = $settings['ipaddr'];
665

    
666
	// If a specific ip address (VIP) is requested, use it.
667
	// Otherwise, if a specific interface is requested, use it
668
	// If "any" interface was selected, local directive will be omitted.
669
	if (is_ipaddrv4($ipaddr)) {
670
		$iface_ip = $ipaddr;
671
	} else {
672
		if ((!empty($interface)) && (strcmp($interface, "any"))) {
673
			$iface_ip=get_interface_ip($interface);
674
		}
675
	}
676
	if (is_ipaddrv6($ipaddr)) {
677
		$iface_ipv6 = $ipaddr;
678
	} else {
679
		if ((!empty($interface)) && (strcmp($interface, "any"))) {
680
			$iface_ipv6=get_interface_ipv6($interface);
681
		}
682
	}
683

    
684

    
685
	$conf = "dev {$devname}\n";
686
	if (isset($settings['verbosity_level'])) {
687
		$conf .= "verb {$settings['verbosity_level']}\n";
688
	}
689

    
690
	$conf .= "dev-type {$settings['dev_mode']}\n";
691
	$conf .= "dev-node /dev/{$tunname}\n";
692
	$conf .= "writepid {$pfile}\n";
693
	$conf .= "#user nobody\n";
694
	$conf .= "#group nobody\n";
695
	$conf .= "script-security 3\n";
696
	$conf .= "daemon\n";
697
	$conf .= "keepalive 10 60\n";
698
	$conf .= "ping-timer-rem\n";
699
	$conf .= "persist-tun\n";
700
	$conf .= "persist-key\n";
701
	$conf .= "proto {$proto}\n";
702
	$conf .= "cipher {$cipher}\n";
703
	$conf .= "auth {$digest}\n";
704
	$conf .= "up /usr/local/sbin/ovpn-linkup\n";
705
	$conf .= "down /usr/local/sbin/ovpn-linkdown\n";
706
	if (file_exists("/usr/local/sbin/openvpn.attributes.sh")) {
707
		switch ($settings['mode']) {
708
			case 'server_user':
709
			case 'server_tls_user':
710
				$conf .= "client-connect /usr/local/sbin/openvpn.attributes.sh\n";
711
				$conf .= "client-disconnect /usr/local/sbin/openvpn.attributes.sh\n";
712
				break;
713
		}
714
	}
715

    
716
	/* Determine the local IP to use - and make sure it matches with the selected protocol. */
717
	if (is_ipaddrv4($iface_ip) && (stristr($settings['protocol'], "6") === false)) {
718
		$conf .= "local {$iface_ip}\n";
719
	} elseif (is_ipaddrv6($iface_ipv6) && (stristr($settings['protocol'], "6") !== false)) {
720
		$conf .= "local {$iface_ipv6}\n";
721
	}
722

    
723
	if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none")) {
724
		$conf .= "engine {$settings['engine']}\n";
725
	}
726

    
727
	// server specific settings
728
	if ($mode == 'server') {
729

    
730
		list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
731
		list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
732
		$mask = gen_subnet_mask($cidr);
733

    
734
		// configure tls modes
735
		switch ($settings['mode']) {
736
			case 'p2p_tls':
737
			case 'server_tls':
738
			case 'server_user':
739
			case 'server_tls_user':
740
				$conf .= "tls-server\n";
741
				break;
742
		}
743

    
744
		// configure p2p/server modes
745
		switch ($settings['mode']) {
746
			case 'p2p_tls':
747
				// If the CIDR is less than a /30, OpenVPN will complain if you try to
748
				//  use the server directive. It works for a single client without it.
749
				//  See ticket #1417
750
				if (!empty($ip) && !empty($mask) && ($cidr < 30)) {
751
					$conf .= "server {$ip} {$mask}\n";
752
					$conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc/server{$vpnid}\n";
753
					if (is_ipaddr($ipv6)) {
754
						$conf .= "server-ipv6 {$ipv6}/{$prefix}\n";
755
					}
756
				}
757
			case 'p2p_shared_key':
758
				if (!empty($ip) && !empty($mask)) {
759
					list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
760
					if ($settings['dev_mode'] == 'tun') {
761
						$conf .= "ifconfig {$ip1} {$ip2}\n";
762
					} else {
763
						$conf .= "ifconfig {$ip1} {$mask}\n";
764
					}
765
				}
766
				if (!empty($ipv6) && !empty($prefix)) {
767
					list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
768
					if ($settings['dev_mode'] == 'tun') {
769
						$conf .= "ifconfig-ipv6 {$ipv6_1} {$ipv6_2}\n";
770
					} else {
771
						$conf .= "ifconfig-ipv6 {$ipv6_1} {$prefix}\n";
772
					}
773
				}
774
				break;
775
			case 'server_tls':
776
			case 'server_user':
777
			case 'server_tls_user':
778
				if (!empty($ip) && !empty($mask)) {
779
					$conf .= "server {$ip} {$mask}\n";
780
					if (is_ipaddr($ipv6)) {
781
						$conf .= "server-ipv6 {$ipv6}/{$prefix}\n";
782
					}
783
					$conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc/server{$vpnid}\n";
784
				} else {
785
					if ($settings['serverbridge_dhcp']) {
786
						if ((!empty($settings['serverbridge_interface'])) && (strcmp($settings['serverbridge_interface'], "none"))) {
787
							$biface_ip=get_interface_ip($settings['serverbridge_interface']);
788
							$biface_sm=gen_subnet_mask(get_interface_subnet($settings['serverbridge_interface']));
789
							if (is_ipaddrv4($biface_ip) && is_ipaddrv4($settings['serverbridge_dhcp_start']) && is_ipaddrv4($settings['serverbridge_dhcp_end'])) {
790
								$conf .= "server-bridge {$biface_ip} {$biface_sm} {$settings['serverbridge_dhcp_start']} {$settings['serverbridge_dhcp_end']}\n";
791
								$conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc/server{$vpnid}\n";
792
							} else {
793
								$conf .= "mode server\n";
794
							}
795
						} else {
796
							$conf .= "mode server\n";
797
						}
798
					}
799
				}
800
				break;
801
		}
802

    
803
		// configure user auth modes
804
		switch ($settings['mode']) {
805
			case 'server_user':
806
				$conf .= "client-cert-not-required\n";
807
			case 'server_tls_user':
808
				/* username-as-common-name is not compatible with server-bridge */
809
				if (stristr($conf, "server-bridge") === false) {
810
					$conf .= "username-as-common-name\n";
811
				}
812
				if (!empty($settings['authmode'])) {
813
					$strictusercn = "false";
814
					if ($settings['strictusercn']) {
815
						$strictusercn = "true";
816
					}
817
					$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";
818
				}
819
				break;
820
		}
821
		if (!isset($settings['cert_depth']) && (strstr($settings['mode'], 'tls'))) {
822
			$settings['cert_depth'] = 1;
823
		}
824
		if (is_numeric($settings['cert_depth'])) {
825
			if (($mode == 'client') && empty($settings['certref'])) {
826
				$cert = "";
827
			} else {
828
				$cert = lookup_cert($settings['certref']);
829
				/* XXX: Seems not used at all! */
830
				$servercn = urlencode(cert_get_cn($cert['crt']));
831
				$conf .= "tls-verify \"/usr/local/sbin/ovpn_auth_verify tls '{$servercn}' {$settings['cert_depth']}\"\n";
832
			}
833
		}
834

    
835
		// The local port to listen on
836
		$conf .= "lport {$settings['local_port']}\n";
837

    
838
		// The management port to listen on
839
		// Use unix socket to overcome the problem on any type of server
840
		$conf .= "management {$g['varetc_path']}/openvpn/{$mode_id}.sock unix\n";
841
		//$conf .= "management 127.0.0.1 {$settings['local_port']}\n";
842

    
843
		if ($settings['maxclients']) {
844
			$conf .= "max-clients {$settings['maxclients']}\n";
845
		}
846

    
847
		// Can we push routes
848
		if ($settings['local_network']) {
849
			$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
850
		}
851
		if ($settings['local_networkv6']) {
852
			$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
853
		}
854

    
855
		switch ($settings['mode']) {
856
			case 'server_tls':
857
			case 'server_user':
858
			case 'server_tls_user':
859
				// Configure client dhcp options
860
				openvpn_add_dhcpopts($settings, $conf);
861
				if ($settings['client2client']) {
862
					$conf .= "client-to-client\n";
863
				}
864
				break;
865
		}
866
		if (isset($settings['duplicate_cn'])) {
867
			$conf .= "duplicate-cn\n";
868
		}
869
	}
870

    
871
	// client specific settings
872

    
873
	if ($mode == 'client') {
874

    
875
		// configure p2p mode
876
		switch ($settings['mode']) {
877
			case 'p2p_tls':
878
				$conf .= "tls-client\n";
879
			case 'shared_key':
880
				$conf .= "client\n";
881
				break;
882
		}
883

    
884
		// If there is no bind option at all (ip and/or port), add "nobind" directive
885
		//  Otherwise, use the local port if defined, failing that, use lport 0 to
886
		//  ensure a random source port.
887
		if ((empty($iface_ip)) && (!$settings['local_port'])) {
888
			$conf .= "nobind\n";
889
		} elseif ($settings['local_port']) {
890
			$conf .= "lport {$settings['local_port']}\n";
891
		} else {
892
			$conf .= "lport 0\n";
893
		}
894

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

    
898
		// The remote server
899
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']}\n";
900

    
901
		if (!empty($settings['use_shaper'])) {
902
			$conf .= "shaper {$settings['use_shaper']}\n";
903
		}
904

    
905
		if (!empty($settings['tunnel_network'])) {
906
			list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
907
			$mask = gen_subnet_mask($cidr);
908
			list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
909
			if ($settings['dev_mode'] == 'tun') {
910
				$conf .= "ifconfig {$ip2} {$ip1}\n";
911
			} else {
912
				$conf .= "ifconfig {$ip2} {$mask}\n";
913
			}
914
		}
915

    
916
		if (!empty($settings['tunnel_networkv6'])) {
917
			list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
918
			list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
919
			if ($settings['dev_mode'] == 'tun') {
920
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$ipv6_1}\n";
921
			} else {
922
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$prefix}\n";
923
			}
924
		}
925

    
926
		if (($settings['auth_user'] || $settings['auth_pass']) && $settings['mode'] == "p2p_tls") {
927
			$up_file = "{$g['varetc_path']}/openvpn/{$mode_id}.up";
928
			$conf .= "auth-user-pass {$up_file}\n";
929
			if ($settings['auth_user']) {
930
				$userpass = "{$settings['auth_user']}\n";
931
			} else {
932
				$userpass = "";
933
			}
934
			if ($settings['auth_pass']) {
935
				$userpass .= "{$settings['auth_pass']}\n";
936
			}
937
			// If only auth_pass is given, then it acts like a user name and we put a blank line where pass would normally go.
938
			if (!($settings['auth_user'] && $settings['auth_pass'])) {
939
				$userpass .= "\n";
940
			}
941
			file_put_contents($up_file, $userpass);
942
		}
943

    
944
		if ($settings['proxy_addr']) {
945
			$conf .= "http-proxy {$settings['proxy_addr']} {$settings['proxy_port']}";
946
			if ($settings['proxy_authtype'] != "none") {
947
				$conf .= " {$g['varetc_path']}/openvpn/{$mode_id}.pas {$settings['proxy_authtype']}";
948
				$proxypas = "{$settings['proxy_user']}\n";
949
				$proxypas .= "{$settings['proxy_passwd']}\n";
950
				file_put_contents("{$g['varetc_path']}/openvpn/{$mode_id}.pas", $proxypas);
951
			}
952
			$conf .= " \n";
953
		}
954
	}
955

    
956
	// Add a remote network route if set, and only for p2p modes.
957
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE)) {
958
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false);
959
	}
960
	// Add a remote network route if set, and only for p2p modes.
961
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE)) {
962
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false);
963
	}
964

    
965
	// Write the settings for the keys
966
	switch ($settings['mode']) {
967
		case 'p2p_shared_key':
968
			openvpn_add_keyfile($settings['shared_key'], $conf, $mode_id, "secret");
969
			break;
970
		case 'p2p_tls':
971
		case 'server_tls':
972
		case 'server_tls_user':
973
		case 'server_user':
974
			// ca_chain() expects parameter to be passed by reference. 
975
			// avoid passing the whole settings array, as param names or 
976
			// types might change in future releases. 
977
			$param = array('caref' => $settings['caref']);	
978
			$ca = ca_chain($param);
979
			$ca = base64_encode($ca);
980
			
981
			openvpn_add_keyfile($ca, $conf, $mode_id, "ca");
982
			
983
			unset($ca, $param);
984

    
985
			if (!empty($settings['certref'])) {
986
				$cert = lookup_cert($settings['certref']);
987
				openvpn_add_keyfile($cert['crt'], $conf, $mode_id, "cert");
988
				openvpn_add_keyfile($cert['prv'], $conf, $mode_id, "key");
989
			}
990
			if ($mode == 'server') {
991
				$conf .= "dh {$g['etc_path']}/dh-parameters.{$settings['dh_length']}\n";
992
			}
993
			if (!empty($settings['crlref'])) {
994
				$crl = lookup_crl($settings['crlref']);
995
				crl_update($crl);
996
				openvpn_add_keyfile($crl['text'], $conf, $mode_id, "crl-verify");
997
			}
998
			if ($settings['tls']) {
999
				if ($mode == "server") {
1000
					$tlsopt = 0;
1001
				} else {
1002
					$tlsopt = 1;
1003
				}
1004
				openvpn_add_keyfile($settings['tls'], $conf, $mode_id, "tls-auth", $tlsopt);
1005
			}
1006
			break;
1007
	}
1008

    
1009
	if (!empty($settings['compression'])) {
1010
		if ($settings['compression'] == "noadapt") {
1011
			$conf .= "comp-noadapt\n";
1012
		} else {
1013
			$conf .= "comp-lzo {$settings['compression']}\n";
1014
		}
1015
	}
1016

    
1017
	if ($settings['passtos']) {
1018
		$conf .= "passtos\n";
1019
	}
1020

    
1021
	if ($settings['resolve_retry']) {
1022
		$conf .= "resolv-retry infinite\n";
1023
	} else if ($mode == 'client') {
1024
		$conf .= "resolv-retry infinite\n";
1025
	}
1026

    
1027
	if ($settings['dynamic_ip']) {
1028
		$conf .= "persist-remote-ip\n";
1029
		$conf .= "float\n";
1030
	}
1031

    
1032
	// If the server is not a TLS server or it has a tunnel network CIDR less than a /30, skip this.
1033
	if (in_array($settings['mode'], $openvpn_tls_server_modes) && (!empty($ip) && !empty($mask) && ($cidr < 30)) && $settings['dev_mode'] != "tap") {
1034
		if (empty($settings['topology'])) {
1035
			$settings['topology'] = "subnet";
1036
		}
1037
		$conf .= "topology {$settings['topology']}\n";
1038
	}
1039

    
1040
	// New client features
1041
	if ($mode == "client") {
1042
		// Dont pull routes checkbox
1043
		if ($settings['route_no_pull']) {
1044
			$conf .= "route-nopull\n";
1045
		}
1046

    
1047
		// Dont add/remove routes checkbox
1048
		if ($settings['route_no_exec']) {
1049
			$conf .= "route-noexec\n";
1050
		}
1051
	}
1052

    
1053
	openvpn_add_custom($settings, $conf);
1054

    
1055
	openvpn_create_dirs();
1056
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.conf";
1057
	file_put_contents($fpath, $conf);
1058
	unset($conf);
1059
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.interface";
1060
	file_put_contents($fpath, $interface);
1061
	//chown($fpath, 'nobody');
1062
	//chgrp($fpath, 'nobody');
1063
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1064
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.interface", 0600);
1065
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.key", 0600);
1066
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.tls-auth", 0600);
1067
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1068
}
1069

    
1070
function openvpn_restart($mode, $settings) {
1071
	global $g, $config;
1072

    
1073
	$vpnid = $settings['vpnid'];
1074
	$mode_id = $mode.$vpnid;
1075
	$lockhandle = lock("openvpnservice{$mode_id}", LOCK_EX);
1076
	/* kill the process if running */
1077
	$pfile = $g['varrun_path']."/openvpn_{$mode_id}.pid";
1078
	if (file_exists($pfile)) {
1079

    
1080
		/* read the pid file */
1081
		$pid = rtrim(file_get_contents($pfile));
1082
		unlink($pfile);
1083

    
1084
		/* send a term signal to the process */
1085
		posix_kill($pid, SIGTERM);
1086

    
1087
		/* wait until the process exits, or timeout and kill it */
1088
		$i = 0;
1089
		while (posix_kill($pid, 0)) {
1090
			usleep(250000);
1091
			if ($i > 10) {
1092
				log_error(sprintf(gettext('OpenVPN ID %1$s PID %2$s still running, killing.'), $mode_id, $pid));
1093
				posix_kill($pid, SIGKILL);
1094
				usleep(500000);
1095
			}
1096
			$i++;
1097
		}
1098
	}
1099

    
1100
	if (isset($settings['disable'])) {
1101
		unlock($lockhandle);
1102
		return;
1103
	}
1104

    
1105
	/* Do not start an instance if we are not CARP master on this vip! */
1106
	if (strstr($settings['interface'], "_vip") && get_carp_interface_status($settings['interface']) != "MASTER") {
1107
		unlock($lockhandle);
1108
		return;
1109
	}
1110

    
1111
	/* Check if client is bound to a gateway group */
1112
	$a_groups = return_gateway_groups_array();
1113
	if (is_array($a_groups[$settings['interface']])) {
1114
		/* the interface is a gateway group. If a vip is defined and its a CARP backup then do not start */
1115
		if (($a_groups[$settings['interface']][0]['vip'] <> "") && (get_carp_interface_status($a_groups[$settings['interface']][0]['vip']) != "MASTER")) {
1116
			unlock($lockhandle);
1117
			return;
1118
		}
1119
	}
1120

    
1121
	/* start the new process */
1122
	$fpath = $g['varetc_path']."/openvpn/{$mode_id}.conf";
1123
	openvpn_clear_route($mode, $settings);
1124
	mwexec("/usr/local/sbin/openvpn --config " . escapeshellarg($fpath));
1125

    
1126
	if (!platform_booting()) {
1127
		send_event("filter reload");
1128
	}
1129
	unlock($lockhandle);
1130
}
1131

    
1132
function openvpn_delete($mode, & $settings) {
1133
	global $g, $config;
1134

    
1135
	$vpnid = $settings['vpnid'];
1136
	$mode_id = $mode.$vpnid;
1137

    
1138
	if (isset($settings['dev_mode'])) {
1139
		$tunname = "{$settings['dev_mode']}{$vpnid}";
1140
	} else {
1141
		/* defaults to tun */
1142
		$tunname = "tun{$vpnid}";
1143
	}
1144

    
1145
	if ($mode == "server") {
1146
		$devname = "ovpns{$vpnid}";
1147
	} else {
1148
		$devname = "ovpnc{$vpnid}";
1149
	}
1150

    
1151
	/* kill the process if running */
1152
	$pfile = "{$g['varrun_path']}/openvpn_{$mode_id}.pid";
1153
	if (file_exists($pfile)) {
1154

    
1155
		/* read the pid file */
1156
		$pid = trim(file_get_contents($pfile));
1157
		unlink($pfile);
1158

    
1159
		/* send a term signal to the process */
1160
		posix_kill($pid, SIGTERM);
1161
	}
1162

    
1163
	/* remove the device from the openvpn group */
1164
	mwexec("/sbin/ifconfig " . escapeshellarg($devname) . " -group openvpn");
1165

    
1166
	/* restore the original adapter name */
1167
	mwexec("/sbin/ifconfig " . escapeshellarg($devname) . " name " . escapeshellarg($tunname));
1168

    
1169
	/* remove the configuration files */
1170
	@array_map('unlink', glob("{$g['varetc_path']}/openvpn/{$mode_id}.*"));
1171
}
1172

    
1173
function openvpn_resync_csc(& $settings) {
1174
	global $g, $config, $openvpn_tls_server_modes;
1175

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

    
1178
	if (isset($settings['disable'])) {
1179
		openvpn_delete_csc($settings);
1180
		return;
1181
	}
1182
	openvpn_create_dirs();
1183

    
1184
	if (empty($settings['server_list'])) {
1185
		$csc_server_list = array();
1186
	} else {
1187
		$csc_server_list = explode(",", $settings['server_list']);
1188
	}
1189

    
1190
	$conf = '';
1191
	if ($settings['block']) {
1192
		$conf .= "disable\n";
1193
	}
1194

    
1195
	if ($settings['push_reset']) {
1196
		$conf .= "push-reset\n";
1197
	}
1198

    
1199
	if ($settings['local_network']) {
1200
		$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1201
	}
1202
	if ($settings['local_networkv6']) {
1203
		$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1204
	}
1205

    
1206
	// Add a remote network iroute if set
1207
	if (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE) {
1208
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false, true);
1209
	}
1210
	// Add a remote network iroute if set
1211
	if (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE) {
1212
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false, true);
1213
	}
1214

    
1215
	openvpn_add_dhcpopts($settings, $conf);
1216

    
1217
	openvpn_add_custom($settings, $conf);
1218
	/* Loop through servers, find which ones can use this CSC */
1219
	if (is_array($config['openvpn']['openvpn-server'])) {
1220
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1221
			if (isset($serversettings['disable'])) {
1222
				continue;
1223
			}
1224
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1225
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1226
					$csc_path = "{$csc_base_path}/server{$serversettings['vpnid']}/" . basename($settings['common_name']);
1227
					$csc_conf = $conf;
1228

    
1229
					if (!empty($serversettings['tunnel_network']) && !empty($settings['tunnel_network'])) {
1230
						list($ip, $mask) = explode('/', trim($settings['tunnel_network']));
1231
						if (($serversettings['dev_mode'] == 'tap') || ($serversettings['topology'] == "subnet")) {
1232
							$csc_conf .= "ifconfig-push {$ip} " . gen_subnet_mask($mask) . "\n";
1233
						} else {
1234
							/* Because this is being pushed, the order from the client's point of view. */
1235
							$baselong = gen_subnetv4($ip, $mask);
1236
							$serverip = ip_after($baselong, 1);
1237
							$clientip = ip_after($baselong, 2);
1238
							$csc_conf .= "ifconfig-push {$clientip} {$serverip}\n";
1239
						}
1240
					}
1241
					file_put_contents($csc_path, $csc_conf);
1242
					chown($csc_path, 'nobody');
1243
					chgrp($csc_path, 'nobody');
1244
				}
1245
			}
1246
		}
1247
	}
1248
}
1249

    
1250
function openvpn_resync_csc_all() {
1251
	global $config;
1252
	if (is_array($config['openvpn']['openvpn-csc'])) {
1253
		foreach ($config['openvpn']['openvpn-csc'] as & $settings) {
1254
			openvpn_resync_csc($settings);
1255
		}
1256
	}
1257
}
1258

    
1259
function openvpn_delete_csc(& $settings) {
1260
	global $g, $config, $openvpn_tls_server_modes;
1261
	$csc_base_path = "{$g['varetc_path']}/openvpn-csc";
1262
	if (empty($settings['server_list'])) {
1263
		$csc_server_list = array();
1264
	} else {
1265
		$csc_server_list = explode(",", $settings['server_list']);
1266
	}
1267

    
1268
	/* Loop through servers, find which ones used this CSC */
1269
	if (is_array($config['openvpn']['openvpn-server'])) {
1270
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1271
			if (isset($serversettings['disable'])) {
1272
				continue;
1273
			}
1274
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1275
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1276
					$csc_path = "{$csc_base_path}/server{$serversettings['vpnid']}/" . basename($settings['common_name']);
1277
					unlink_if_exists($csc_path);
1278
				}
1279
			}
1280
		}
1281
	}
1282
}
1283

    
1284
// Resync the configuration and restart the VPN
1285
function openvpn_resync($mode, $settings) {
1286
	openvpn_reconfigure($mode, $settings);
1287
	openvpn_restart($mode, $settings);
1288
}
1289

    
1290
// Resync and restart all VPNs
1291
function openvpn_resync_all($interface = "") {
1292
	global $g, $config;
1293

    
1294
	openvpn_create_dirs();
1295

    
1296
	if (!is_array($config['openvpn'])) {
1297
		$config['openvpn'] = array();
1298
	}
1299

    
1300
/*
1301
	if (!$config['openvpn']['dh-parameters']) {
1302
		echo "Configuring OpenVPN Parameters ...\n";
1303
		$dh_parameters = openvpn_create_dhparams(1024);
1304
		$dh_parameters = base64_encode($dh_parameters);
1305
		$config['openvpn']['dh-parameters'] = $dh_parameters;
1306
		write_config("OpenVPN DH parameters");
1307
	}
1308

    
1309
	$path_ovdh = $g['varetc_path']."/openvpn/dh-parameters";
1310
	if (!file_exists($path_ovdh)) {
1311
		$dh_parameters = $config['openvpn']['dh-parameters'];
1312
		$dh_parameters = base64_decode($dh_parameters);
1313
		file_put_contents($path_ovdh, $dh_parameters);
1314
	}
1315
*/
1316
	if ($interface <> "") {
1317
		log_error(sprintf(gettext("Resyncing OpenVPN instances for interface %s."), convert_friendly_interface_to_friendly_descr($interface)));
1318
	} else {
1319
		log_error(gettext("Resyncing OpenVPN instances."));
1320
	}
1321

    
1322
	if (is_array($config['openvpn']['openvpn-server'])) {
1323
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1324
			if ($interface <> "" && $interface != $settings['interface']) {
1325
				continue;
1326
			}
1327
			openvpn_resync('server', $settings);
1328
		}
1329
	}
1330

    
1331
	if (is_array($config['openvpn']['openvpn-client'])) {
1332
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1333
			if ($interface <> "" && $interface != $settings['interface']) {
1334
				continue;
1335
			}
1336
			openvpn_resync('client', $settings);
1337
		}
1338
	}
1339

    
1340
	openvpn_resync_csc_all();
1341

    
1342
}
1343

    
1344
// Resync and restart all VPNs using a gateway group.
1345
function openvpn_resync_gwgroup($gwgroupname = "") {
1346
	global $g, $config;
1347

    
1348
	if ($gwgroupname <> "") {
1349
		if (is_array($config['openvpn']['openvpn-server'])) {
1350
			foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1351
				if ($gwgroupname == $settings['interface']) {
1352
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s server %2$s.'), $gwgroupname, $settings["description"]));
1353
					openvpn_resync('server', $settings);
1354
				}
1355
			}
1356
		}
1357

    
1358
		if (is_array($config['openvpn']['openvpn-client'])) {
1359
			foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1360
				if ($gwgroupname == $settings['interface']) {
1361
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s client %2$s.'), $gwgroupname, $settings["description"]));
1362
					openvpn_resync('client', $settings);
1363
				}
1364
			}
1365
		}
1366

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

    
1369
	} else {
1370
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1371
	}
1372
}
1373

    
1374
function openvpn_get_active_servers($type="multipoint") {
1375
	global $config, $g;
1376

    
1377
	$servers = array();
1378
	if (is_array($config['openvpn']['openvpn-server'])) {
1379
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1380
			if (empty($settings) || isset($settings['disable'])) {
1381
				continue;
1382
			}
1383

    
1384
			$prot = $settings['protocol'];
1385
			$port = $settings['local_port'];
1386

    
1387
			$server = array();
1388
			$server['port'] = ($settings['local_port']) ? $settings['local_port'] : 1194;
1389
			$server['mode'] = $settings['mode'];
1390
			if ($settings['description']) {
1391
				$server['name'] = "{$settings['description']} {$prot}:{$port}";
1392
			} else {
1393
				$server['name'] = "Server {$prot}:{$port}";
1394
			}
1395
			$server['conns'] = array();
1396
			$server['vpnid'] = $settings['vpnid'];
1397
			$server['mgmt'] = "server{$server['vpnid']}";
1398
			$socket = "unix://{$g['varetc_path']}/openvpn/{$server['mgmt']}.sock";
1399
			list($tn, $sm) = explode('/', trim($settings['tunnel_network']));
1400

    
1401
			if ((($server['mode'] == "p2p_shared_key") || ($sm >= 30)) && ($type == "p2p")) {
1402
				$servers[] = openvpn_get_client_status($server, $socket);
1403
			} elseif (($server['mode'] != "p2p_shared_key") && ($type == "multipoint") && ($sm < 30)) {
1404
				$servers[] = openvpn_get_server_status($server, $socket);
1405
			}
1406
		}
1407
	}
1408
	return $servers;
1409
}
1410

    
1411
function openvpn_get_server_status($server, $socket) {
1412
	$errval = null;
1413
	$errstr = null;
1414
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1415
	if ($fp) {
1416
		stream_set_timeout($fp, 1);
1417

    
1418
		/* send our status request */
1419
		fputs($fp, "status 2\n");
1420

    
1421
		/* recv all response lines */
1422
		while (!feof($fp)) {
1423

    
1424
			/* read the next line */
1425
			$line = fgets($fp, 1024);
1426

    
1427
			$info = stream_get_meta_data($fp);
1428
			if ($info['timed_out']) {
1429
				break;
1430
			}
1431

    
1432
			/* parse header list line */
1433
			if (strstr($line, "HEADER")) {
1434
				continue;
1435
			}
1436

    
1437
			/* parse end of output line */
1438
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1439
				break;
1440
			}
1441

    
1442
			/* parse client list line */
1443
			if (strstr($line, "CLIENT_LIST")) {
1444
				$list = explode(",", $line);
1445
				$conn = array();
1446
				$conn['common_name'] = $list[1];
1447
				$conn['remote_host'] = $list[2];
1448
				$conn['virtual_addr'] = $list[3];
1449
				$conn['virtual_addr6'] = $list[4];
1450
				$conn['bytes_recv'] = $list[5];
1451
				$conn['bytes_sent'] = $list[6];
1452
				$conn['connect_time'] = $list[7];
1453
				$conn['connect_time_unix'] = $list[8];
1454
				$conn['user_name'] = $list[9];
1455
				$conn['client_id'] = $list[10];
1456
				$conn['peer_id'] = $list[11];
1457
				$server['conns'][] = $conn;
1458
			}
1459
			/* parse routing table lines */
1460
			if (strstr($line, "ROUTING_TABLE")) {
1461
				$list = explode(",", $line);
1462
				$conn = array();
1463
				$conn['virtual_addr'] = $list[1];
1464
				$conn['common_name'] = $list[2];
1465
				$conn['remote_host'] = $list[3];
1466
				$conn['last_time'] = $list[4];
1467
				$server['routes'][] = $conn;
1468
			}
1469
		}
1470

    
1471
		/* cleanup */
1472
		fclose($fp);
1473
	} else {
1474
		$conn = array();
1475
		$conn['common_name'] = "[error]";
1476
		$conn['remote_host'] = gettext("Unable to contact daemon");
1477
		$conn['virtual_addr'] = gettext("Service not running?");
1478
		$conn['bytes_recv'] = 0;
1479
		$conn['bytes_sent'] = 0;
1480
		$conn['connect_time'] = 0;
1481
		$server['conns'][] = $conn;
1482
	}
1483
	return $server;
1484
}
1485

    
1486
function openvpn_get_active_clients() {
1487
	global $config, $g;
1488

    
1489
	$clients = array();
1490
	if (is_array($config['openvpn']['openvpn-client'])) {
1491
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1492

    
1493
			if (empty($settings) || isset($settings['disable'])) {
1494
				continue;
1495
			}
1496

    
1497
			$prot = $settings['protocol'];
1498
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
1499

    
1500
			$client = array();
1501
			$client['port'] = $settings['local_port'];
1502
			if ($settings['description']) {
1503
				$client['name'] = "{$settings['description']} {$prot}{$port}";
1504
			} else {
1505
				$client['name'] = "Client {$prot}{$port}";
1506
			}
1507

    
1508
			$client['vpnid'] = $settings['vpnid'];
1509
			$client['mgmt'] = "client{$client['vpnid']}";
1510
			$socket = "unix://{$g['varetc_path']}/openvpn/{$client['mgmt']}.sock";
1511
			$client['status']="down";
1512

    
1513
			$clients[] = openvpn_get_client_status($client, $socket);
1514
		}
1515
	}
1516
	return $clients;
1517
}
1518

    
1519
function openvpn_get_client_status($client, $socket) {
1520
	$errval = null;
1521
	$errstr = null;
1522
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1523
	if ($fp) {
1524
		stream_set_timeout($fp, 1);
1525
		/* send our status request */
1526
		fputs($fp, "state 1\n");
1527

    
1528
		/* recv all response lines */
1529
		while (!feof($fp)) {
1530
			/* read the next line */
1531
			$line = fgets($fp, 1024);
1532

    
1533
			$info = stream_get_meta_data($fp);
1534
			if ($info['timed_out']) {
1535
				break;
1536
			}
1537

    
1538
			/* Get the client state */
1539
			if (strstr($line, "CONNECTED")) {
1540
				$client['status'] = "up";
1541
				$list = explode(",", $line);
1542

    
1543
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1544
				$client['virtual_addr'] = $list[3];
1545
				$client['remote_host'] = $list[4];
1546
				$client['remote_port'] = $list[5];
1547
				$client['local_host'] = $list[6];
1548
				$client['local_port'] = $list[7];
1549
				$client['virtual_addr6'] = $list[8];
1550
			}
1551
			if (strstr($line, "CONNECTING")) {
1552
				$client['status'] = "connecting";
1553
			}
1554
			if (strstr($line, "ASSIGN_IP")) {
1555
				$client['status'] = "waiting";
1556
				$list = explode(",", $line);
1557

    
1558
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1559
				$client['virtual_addr'] = $list[3];
1560
			}
1561
			if (strstr($line, "RECONNECTING")) {
1562
				$client['status'] = "reconnecting";
1563
				$list = explode(",", $line);
1564

    
1565
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1566
				$client['status'] .= "; " . $list[2];
1567
			}
1568
			/* parse end of output line */
1569
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1570
				break;
1571
			}
1572
		}
1573

    
1574
		/* If up, get read/write stats */
1575
		if (strcmp($client['status'], "up") == 0) {
1576
			fputs($fp, "status 2\n");
1577
			/* recv all response lines */
1578
			while (!feof($fp)) {
1579
				/* read the next line */
1580
				$line = fgets($fp, 1024);
1581

    
1582
				$info = stream_get_meta_data($fp);
1583
				if ($info['timed_out']) {
1584
					break;
1585
				}
1586

    
1587
				if (strstr($line, "TCP/UDP read bytes")) {
1588
					$list = explode(",", $line);
1589
					$client['bytes_recv'] = $list[1];
1590
				}
1591

    
1592
				if (strstr($line, "TCP/UDP write bytes")) {
1593
					$list = explode(",", $line);
1594
					$client['bytes_sent'] = $list[1];
1595
				}
1596

    
1597
				/* parse end of output line */
1598
				if (strstr($line, "END")) {
1599
					break;
1600
				}
1601
			}
1602
		}
1603

    
1604
		fclose($fp);
1605

    
1606
	} else {
1607
		$client['remote_host'] = gettext("Unable to contact daemon");
1608
		$client['virtual_addr'] = gettext("Service not running?");
1609
		$client['bytes_recv'] = 0;
1610
		$client['bytes_sent'] = 0;
1611
		$client['connect_time'] = 0;
1612
	}
1613
	return $client;
1614
}
1615

    
1616
function openvpn_kill_client($port, $remipp) {
1617
	global $g;
1618

    
1619
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
1620
	$tcpsrv = "unix://{$g['varetc_path']}/openvpn/{$port}.sock";
1621
	$errval = null;
1622
	$errstr = null;
1623

    
1624
	/* open a tcp connection to the management port of each server */
1625
	$fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
1626
	$killed = -1;
1627
	if ($fp) {
1628
		stream_set_timeout($fp, 1);
1629
		fputs($fp, "kill {$remipp}\n");
1630
		while (!feof($fp)) {
1631
			$line = fgets($fp, 1024);
1632

    
1633
			$info = stream_get_meta_data($fp);
1634
			if ($info['timed_out']) {
1635
				break;
1636
			}
1637

    
1638
			/* parse header list line */
1639
			if (strpos($line, "INFO:") !== false) {
1640
				continue;
1641
			}
1642
			if (strpos($line, "SUCCESS") !== false) {
1643
				$killed = 0;
1644
			}
1645
			break;
1646
		}
1647
		fclose($fp);
1648
	}
1649
	return $killed;
1650
}
1651

    
1652
function openvpn_refresh_crls() {
1653
	global $g, $config;
1654

    
1655
	openvpn_create_dirs();
1656

    
1657
	if (is_array($config['openvpn']['openvpn-server'])) {
1658
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
1659
			if (empty($settings)) {
1660
				continue;
1661
			}
1662
			if (isset($settings['disable'])) {
1663
				continue;
1664
			}
1665
			// Write the settings for the keys
1666
			switch ($settings['mode']) {
1667
				case 'p2p_tls':
1668
				case 'server_tls':
1669
				case 'server_tls_user':
1670
				case 'server_user':
1671
					if (!empty($settings['crlref'])) {
1672
						$crl = lookup_crl($settings['crlref']);
1673
						crl_update($crl);
1674
						$fpath = $g['varetc_path']."/openvpn/server{$settings['vpnid']}.crl-verify";
1675
						file_put_contents($fpath, base64_decode($crl['text']));
1676
						@chmod($fpath, 0644);
1677
					}
1678
					break;
1679
			}
1680
		}
1681
	}
1682
}
1683

    
1684
function openvpn_create_dirs() {
1685
	global $g, $config, $openvpn_tls_server_modes;
1686
	if (!is_dir("{$g['varetc_path']}/openvpn")) {
1687
		safe_mkdir("{$g['varetc_path']}/openvpn", 0750);
1688
	}
1689
	if (!is_dir("{$g['varetc_path']}/openvpn-csc")) {
1690
		safe_mkdir("{$g['varetc_path']}/openvpn-csc", 0750);
1691
	}
1692

    
1693
	/* Check for enabled servers and create server-specific CSC dirs */
1694
	if (is_array($config['openvpn']['openvpn-server'])) {
1695
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
1696
			if (isset($settings['disable'])) {
1697
				continue;
1698
			}
1699
			if (in_array($settings['mode'], $openvpn_tls_server_modes)) {
1700
				if ($settings['vpnid']) {
1701
					safe_mkdir("{$g['varetc_path']}/openvpn-csc/server{$settings['vpnid']}");
1702
				}
1703
			}
1704
		}
1705
	}
1706
}
1707

    
1708
function openvpn_get_interface_ip($ip, $cidr) {
1709
	$subnet = gen_subnetv4($ip, $cidr);
1710
	$ip1 = ip_after($subnet);
1711
	$ip2 = ip_after($ip1);
1712
	return array($ip1, $ip2);
1713
}
1714

    
1715
function openvpn_get_interface_ipv6($ipv6, $prefix) {
1716
	$basev6 = gen_subnetv6($ipv6, $prefix);
1717
	// Is there a better way to do this math?
1718
	$ipv6_arr = explode(':', $basev6);
1719
	$last = hexdec(array_pop($ipv6_arr));
1720
	$ipv6_1 = Net_IPv6::compress(Net_IPv6::uncompress(implode(':', $ipv6_arr) . ':' . dechex($last + 1)));
1721
	$ipv6_2 = Net_IPv6::compress(Net_IPv6::uncompress(implode(':', $ipv6_arr) . ':' . dechex($last + 2)));
1722
	return array($ipv6_1, $ipv6_2);
1723
}
1724

    
1725
function openvpn_clear_route($mode, $settings) {
1726
	if (empty($settings['tunnel_network'])) {
1727
		return;
1728
	}
1729
	list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
1730
	$mask = gen_subnet_mask($cidr);
1731
	$clear_route = false;
1732

    
1733
	switch ($settings['mode']) {
1734
		case 'shared_key':
1735
			$clear_route = true;
1736
			break;
1737
		case 'p2p_tls':
1738
		case 'p2p_shared_key':
1739
			if ($cidr == 30) {
1740
				$clear_route = true;
1741
			}
1742
			break;
1743
	}
1744

    
1745
	if ($clear_route && !empty($ip) && !empty($mask)) {
1746
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1747
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
1748
		/* XXX: Family for route? */
1749
		mwexec("/sbin/route -q delete {$ip_to_clear}");
1750
	}
1751
}
1752

    
1753
function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) {
1754
	$routes = "";
1755
	if (empty($value)) {
1756
		return "";
1757
	}
1758
	$networks = explode(',', $value);
1759

    
1760
	foreach ($networks as $network) {
1761
		if ($ipproto == "ipv4") {
1762
			$route = openvpn_gen_route_ipv4($network, $iroute);
1763
		} else {
1764
			$route = openvpn_gen_route_ipv6($network, $iroute);
1765
		}
1766

    
1767
		if ($push) {
1768
			$routes .= "push \"{$route}\"\n";
1769
		} else {
1770
			$routes .= "{$route}\n";
1771
		}
1772
	}
1773
	return $routes;
1774
}
1775

    
1776
function openvpn_gen_route_ipv4($network, $iroute = false) {
1777
	$i = ($iroute) ? "i" : "";
1778
	list($ip, $mask) = explode('/', trim($network));
1779
	$mask = gen_subnet_mask($mask);
1780
	return "{$i}route $ip $mask";
1781
}
1782

    
1783
function openvpn_gen_route_ipv6($network, $iroute = false) {
1784
	$i = ($iroute) ? "i" : "";
1785
	list($ipv6, $prefix) = explode('/', trim($network));
1786
	if (empty($prefix)) {
1787
		$prefix = "128";
1788
	}
1789
	return "{$i}route-ipv6 ${ipv6}/${prefix}";
1790
}
1791

    
1792
function openvpn_get_settings($mode, $vpnid) {
1793
	global $config;
1794

    
1795
	if (is_array($config['openvpn']['openvpn-server'])) {
1796
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
1797
			if (isset($settings['disable'])) {
1798
				continue;
1799
			}
1800

    
1801
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
1802
				return $settings;
1803
			}
1804
		}
1805
	}
1806

    
1807
	if (is_array($config['openvpn']['openvpn-client'])) {
1808
		foreach ($config['openvpn']['openvpn-client'] as $settings) {
1809
			if (isset($settings['disable'])) {
1810
				continue;
1811
			}
1812

    
1813
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
1814
				return $settings;
1815
			}
1816
		}
1817
	}
1818

    
1819
	return array();
1820
}
1821

    
1822
function openvpn_restart_by_vpnid($mode, $vpnid) {
1823
	$settings = openvpn_get_settings($mode, $vpnid);
1824
	openvpn_restart($mode, $settings);
1825
}
1826

    
1827
?>
(28-28/51)