Project

General

Profile

Download (50.9 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * openvpn.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2006 Fernando Lemos
7
 * Copyright (c) 2006-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
	switch ($settings['dev_mode']) {
692
		case "tun":
693
			if (!$settings['no_tun_ipv6']) {
694
				$conf .= "tun-ipv6\n";
695
			}
696
			break;
697
	}
698
	$conf .= "dev-node /dev/{$tunname}\n";
699
	$conf .= "writepid {$pfile}\n";
700
	$conf .= "#user nobody\n";
701
	$conf .= "#group nobody\n";
702
	$conf .= "script-security 3\n";
703
	$conf .= "daemon\n";
704
	$conf .= "keepalive 10 60\n";
705
	$conf .= "ping-timer-rem\n";
706
	$conf .= "persist-tun\n";
707
	$conf .= "persist-key\n";
708
	$conf .= "proto {$proto}\n";
709
	$conf .= "cipher {$cipher}\n";
710
	$conf .= "auth {$digest}\n";
711
	$conf .= "up /usr/local/sbin/ovpn-linkup\n";
712
	$conf .= "down /usr/local/sbin/ovpn-linkdown\n";
713
	if (file_exists("/usr/local/sbin/openvpn.attributes.sh")) {
714
		switch ($settings['mode']) {
715
			case 'server_user':
716
			case 'server_tls_user':
717
				$conf .= "client-connect /usr/local/sbin/openvpn.attributes.sh\n";
718
				$conf .= "client-disconnect /usr/local/sbin/openvpn.attributes.sh\n";
719
				break;
720
		}
721
	}
722

    
723
	/* Determine the local IP to use - and make sure it matches with the selected protocol. */
724
	if (is_ipaddrv4($iface_ip) && (stristr($settings['protocol'], "6") === false)) {
725
		$conf .= "local {$iface_ip}\n";
726
	} elseif (is_ipaddrv6($iface_ipv6) && (stristr($settings['protocol'], "6") !== false)) {
727
		$conf .= "local {$iface_ipv6}\n";
728
	}
729

    
730
	if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none")) {
731
		$conf .= "engine {$settings['engine']}\n";
732
	}
733

    
734
	// server specific settings
735
	if ($mode == 'server') {
736

    
737
		list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
738
		list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
739
		$mask = gen_subnet_mask($cidr);
740

    
741
		// configure tls modes
742
		switch ($settings['mode']) {
743
			case 'p2p_tls':
744
			case 'server_tls':
745
			case 'server_user':
746
			case 'server_tls_user':
747
				$conf .= "tls-server\n";
748
				break;
749
		}
750

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

    
810
		// configure user auth modes
811
		switch ($settings['mode']) {
812
			case 'server_user':
813
				$conf .= "client-cert-not-required\n";
814
			case 'server_tls_user':
815
				/* username-as-common-name is not compatible with server-bridge */
816
				if (stristr($conf, "server-bridge") === false) {
817
					$conf .= "username-as-common-name\n";
818
				}
819
				if (!empty($settings['authmode'])) {
820
					$strictusercn = "false";
821
					if ($settings['strictusercn']) {
822
						$strictusercn = "true";
823
					}
824
					$conf .= "auth-user-pass-verify \"/usr/local/sbin/ovpn_auth_verify user '{$settings['authmode']}' {$strictusercn} {$mode_id} {$settings['local_port']}\" via-env\n";
825
				}
826
				break;
827
		}
828
		if (!isset($settings['cert_depth']) && (strstr($settings['mode'], 'tls'))) {
829
			$settings['cert_depth'] = 1;
830
		}
831
		if (is_numeric($settings['cert_depth'])) {
832
			if (($mode == 'client') && empty($settings['certref'])) {
833
				$cert = "";
834
			} else {
835
				$cert = lookup_cert($settings['certref']);
836
				/* XXX: Seems not used at all! */
837
				$servercn = urlencode(cert_get_cn($cert['crt']));
838
				$conf .= "tls-verify \"/usr/local/sbin/ovpn_auth_verify tls '{$servercn}' {$settings['cert_depth']}\"\n";
839
			}
840
		}
841

    
842
		// The local port to listen on
843
		$conf .= "lport {$settings['local_port']}\n";
844

    
845
		// The management port to listen on
846
		// Use unix socket to overcome the problem on any type of server
847
		$conf .= "management {$g['varetc_path']}/openvpn/{$mode_id}.sock unix\n";
848
		//$conf .= "management 127.0.0.1 {$settings['local_port']}\n";
849

    
850
		if ($settings['maxclients']) {
851
			$conf .= "max-clients {$settings['maxclients']}\n";
852
		}
853

    
854
		// Can we push routes
855
		if ($settings['local_network']) {
856
			$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
857
		}
858
		if ($settings['local_networkv6']) {
859
			$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
860
		}
861

    
862
		switch ($settings['mode']) {
863
			case 'server_tls':
864
			case 'server_user':
865
			case 'server_tls_user':
866
				// Configure client dhcp options
867
				openvpn_add_dhcpopts($settings, $conf);
868
				if ($settings['client2client']) {
869
					$conf .= "client-to-client\n";
870
				}
871
				break;
872
		}
873
		if (isset($settings['duplicate_cn'])) {
874
			$conf .= "duplicate-cn\n";
875
		}
876
	}
877

    
878
	// client specific settings
879

    
880
	if ($mode == 'client') {
881

    
882
		// configure p2p mode
883
		switch ($settings['mode']) {
884
			case 'p2p_tls':
885
				$conf .= "tls-client\n";
886
			case 'shared_key':
887
				$conf .= "client\n";
888
				break;
889
		}
890

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

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

    
905
		// The remote server
906
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']}\n";
907

    
908
		if (!empty($settings['use_shaper'])) {
909
			$conf .= "shaper {$settings['use_shaper']}\n";
910
		}
911

    
912
		if (!empty($settings['tunnel_network'])) {
913
			list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
914
			$mask = gen_subnet_mask($cidr);
915
			list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
916
			if ($settings['dev_mode'] == 'tun') {
917
				$conf .= "ifconfig {$ip2} {$ip1}\n";
918
			} else {
919
				$conf .= "ifconfig {$ip2} {$mask}\n";
920
			}
921
		}
922

    
923
		if (!empty($settings['tunnel_networkv6'])) {
924
			list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
925
			list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
926
			if ($settings['dev_mode'] == 'tun') {
927
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$ipv6_1}\n";
928
			} else {
929
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$prefix}\n";
930
			}
931
		}
932

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

    
951
		if ($settings['proxy_addr']) {
952
			$conf .= "http-proxy {$settings['proxy_addr']} {$settings['proxy_port']}";
953
			if ($settings['proxy_authtype'] != "none") {
954
				$conf .= " {$g['varetc_path']}/openvpn/{$mode_id}.pas {$settings['proxy_authtype']}";
955
				$proxypas = "{$settings['proxy_user']}\n";
956
				$proxypas .= "{$settings['proxy_passwd']}\n";
957
				file_put_contents("{$g['varetc_path']}/openvpn/{$mode_id}.pas", $proxypas);
958
			}
959
			$conf .= " \n";
960
		}
961
	}
962

    
963
	// Add a remote network route if set, and only for p2p modes.
964
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE)) {
965
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false);
966
	}
967
	// Add a remote network route if set, and only for p2p modes.
968
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE)) {
969
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false);
970
	}
971

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

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

    
1016
	if (!empty($settings['compression'])) {
1017
		if ($settings['compression'] == "noadapt") {
1018
			$conf .= "comp-noadapt\n";
1019
		} else {
1020
			$conf .= "comp-lzo {$settings['compression']}\n";
1021
		}
1022
	}
1023

    
1024
	if ($settings['passtos']) {
1025
		$conf .= "passtos\n";
1026
	}
1027

    
1028
	if ($settings['resolve_retry']) {
1029
		$conf .= "resolv-retry infinite\n";
1030
	} else if ($mode == 'client') {
1031
		$conf .= "resolv-retry infinite\n";
1032
	}
1033

    
1034
	if ($settings['dynamic_ip']) {
1035
		$conf .= "persist-remote-ip\n";
1036
		$conf .= "float\n";
1037
	}
1038

    
1039
	// If the server is not a TLS server or it has a tunnel network CIDR less than a /30, skip this.
1040
	if (in_array($settings['mode'], $openvpn_tls_server_modes) && (!empty($ip) && !empty($mask) && ($cidr < 30)) && $settings['dev_mode'] != "tap") {
1041
		if (empty($settings['topology'])) {
1042
			$settings['topology'] = "subnet";
1043
		}
1044
		$conf .= "topology {$settings['topology']}\n";
1045
	}
1046

    
1047
	// New client features
1048
	if ($mode == "client") {
1049
		// Dont pull routes checkbox
1050
		if ($settings['route_no_pull']) {
1051
			$conf .= "route-nopull\n";
1052
		}
1053

    
1054
		// Dont add/remove routes checkbox
1055
		if ($settings['route_no_exec']) {
1056
			$conf .= "route-noexec\n";
1057
		}
1058
	}
1059

    
1060
	openvpn_add_custom($settings, $conf);
1061

    
1062
	openvpn_create_dirs();
1063
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.conf";
1064
	file_put_contents($fpath, $conf);
1065
	unset($conf);
1066
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.interface";
1067
	file_put_contents($fpath, $interface);
1068
	//chown($fpath, 'nobody');
1069
	//chgrp($fpath, 'nobody');
1070
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1071
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.interface", 0600);
1072
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.key", 0600);
1073
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.tls-auth", 0600);
1074
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1075
}
1076

    
1077
function openvpn_restart($mode, $settings) {
1078
	global $g, $config;
1079

    
1080
	$vpnid = $settings['vpnid'];
1081
	$mode_id = $mode.$vpnid;
1082

    
1083
	/* kill the process if running */
1084
	$pfile = $g['varrun_path']."/openvpn_{$mode_id}.pid";
1085
	if (file_exists($pfile)) {
1086

    
1087
		/* read the pid file */
1088
		$pid = rtrim(file_get_contents($pfile));
1089
		unlink($pfile);
1090

    
1091
		/* send a term signal to the process */
1092
		posix_kill($pid, SIGTERM);
1093

    
1094
		/* wait until the process exits, or timeout and kill it */
1095
		$i = 0;
1096
		while (posix_kill($pid, 0)) {
1097
			usleep(250000);
1098
			if ($i > 10) {
1099
				log_error(sprintf(gettext('OpenVPN ID %1$s PID %2$s still running, killing.'), $mode_id, $pid));
1100
				posix_kill($pid, SIGKILL);
1101
				usleep(500000);
1102
			}
1103
			$i++;
1104
		}
1105
	}
1106

    
1107
	if (isset($settings['disable'])) {
1108
		return;
1109
	}
1110

    
1111
	/* Do not start an instance if we are not CARP master on this vip! */
1112
	if (strstr($settings['interface'], "_vip") && get_carp_interface_status($settings['interface']) != "MASTER") {
1113
		return;
1114
	}
1115

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

    
1125
	/* start the new process */
1126
	$fpath = $g['varetc_path']."/openvpn/{$mode_id}.conf";
1127
	openvpn_clear_route($mode, $settings);
1128
	mwexec_bg("/usr/local/sbin/openvpn --config " . escapeshellarg($fpath));
1129

    
1130
	if (!platform_booting()) {
1131
		send_event("filter reload");
1132
	}
1133
}
1134

    
1135
function openvpn_delete($mode, & $settings) {
1136
	global $g, $config;
1137

    
1138
	$vpnid = $settings['vpnid'];
1139
	$mode_id = $mode.$vpnid;
1140

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

    
1148
	if ($mode == "server") {
1149
		$devname = "ovpns{$vpnid}";
1150
	} else {
1151
		$devname = "ovpnc{$vpnid}";
1152
	}
1153

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

    
1158
		/* read the pid file */
1159
		$pid = trim(file_get_contents($pfile));
1160
		unlink($pfile);
1161

    
1162
		/* send a term signal to the process */
1163
		posix_kill($pid, SIGTERM);
1164
	}
1165

    
1166
	/* remove the device from the openvpn group */
1167
	mwexec("/sbin/ifconfig " . escapeshellarg($devname) . " -group openvpn");
1168

    
1169
	/* restore the original adapter name */
1170
	mwexec("/sbin/ifconfig " . escapeshellarg($devname) . " name " . escapeshellarg($tunname));
1171

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

    
1176
function openvpn_resync_csc(& $settings) {
1177
	global $g, $config, $openvpn_tls_server_modes;
1178

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

    
1181
	if (isset($settings['disable'])) {
1182
		openvpn_delete_csc($settings);
1183
		return;
1184
	}
1185
	openvpn_create_dirs();
1186

    
1187
	if (empty($settings['server_list'])) {
1188
		$csc_server_list = array();
1189
	} else {
1190
		$csc_server_list = explode(",", $settings['server_list']);
1191
	}
1192

    
1193
	$conf = '';
1194
	if ($settings['block']) {
1195
		$conf .= "disable\n";
1196
	}
1197

    
1198
	if ($settings['push_reset']) {
1199
		$conf .= "push-reset\n";
1200
	}
1201

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

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

    
1218
	openvpn_add_dhcpopts($settings, $conf);
1219

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

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

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

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

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

    
1287
// Resync the configuration and restart the VPN
1288
function openvpn_resync($mode, $settings) {
1289
	openvpn_reconfigure($mode, $settings);
1290
	openvpn_restart($mode, $settings);
1291
}
1292

    
1293
// Resync and restart all VPNs
1294
function openvpn_resync_all($interface = "") {
1295
	global $g, $config;
1296

    
1297
	openvpn_create_dirs();
1298

    
1299
	if (!is_array($config['openvpn'])) {
1300
		$config['openvpn'] = array();
1301
	}
1302

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

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

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

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

    
1343
	openvpn_resync_csc_all();
1344

    
1345
}
1346

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

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

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

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

    
1372
	} else {
1373
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1374
	}
1375
}
1376

    
1377
function openvpn_get_active_servers($type="multipoint") {
1378
	global $config, $g;
1379

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

    
1387
			$prot = $settings['protocol'];
1388
			$port = $settings['local_port'];
1389

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

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

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

    
1421
		/* send our status request */
1422
		fputs($fp, "status 2\n");
1423

    
1424
		/* recv all response lines */
1425
		while (!feof($fp)) {
1426

    
1427
			/* read the next line */
1428
			$line = fgets($fp, 1024);
1429

    
1430
			$info = stream_get_meta_data($fp);
1431
			if ($info['timed_out']) {
1432
				break;
1433
			}
1434

    
1435
			/* parse header list line */
1436
			if (strstr($line, "HEADER")) {
1437
				continue;
1438
			}
1439

    
1440
			/* parse end of output line */
1441
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1442
				break;
1443
			}
1444

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

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

    
1484
function openvpn_get_active_clients() {
1485
	global $config, $g;
1486

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

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

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

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

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

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

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

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

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

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

    
1541
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1542
				$client['virtual_addr'] = $list[3];
1543
				$client['remote_host'] = $list[4];
1544
			}
1545
			if (strstr($line, "CONNECTING")) {
1546
				$client['status'] = "connecting";
1547
			}
1548
			if (strstr($line, "ASSIGN_IP")) {
1549
				$client['status'] = "waiting";
1550
				$list = explode(",", $line);
1551

    
1552
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1553
				$client['virtual_addr'] = $list[3];
1554
			}
1555
			if (strstr($line, "RECONNECTING")) {
1556
				$client['status'] = "reconnecting";
1557
				$list = explode(",", $line);
1558

    
1559
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1560
				$client['status'] .= "; " . $list[2];
1561
			}
1562
			/* parse end of output line */
1563
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1564
				break;
1565
			}
1566
		}
1567

    
1568
		/* If up, get read/write stats */
1569
		if (strcmp($client['status'], "up") == 0) {
1570
			fputs($fp, "status 2\n");
1571
			/* recv all response lines */
1572
			while (!feof($fp)) {
1573
				/* read the next line */
1574
				$line = fgets($fp, 1024);
1575

    
1576
				$info = stream_get_meta_data($fp);
1577
				if ($info['timed_out']) {
1578
					break;
1579
				}
1580

    
1581
				if (strstr($line, "TCP/UDP read bytes")) {
1582
					$list = explode(",", $line);
1583
					$client['bytes_recv'] = $list[1];
1584
				}
1585

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

    
1591
				/* parse end of output line */
1592
				if (strstr($line, "END")) {
1593
					break;
1594
				}
1595
			}
1596
		}
1597

    
1598
		fclose($fp);
1599

    
1600
	} else {
1601
		$client['remote_host'] = gettext("Unable to contact daemon");
1602
		$client['virtual_addr'] = gettext("Service not running?");
1603
		$client['bytes_recv'] = 0;
1604
		$client['bytes_sent'] = 0;
1605
		$client['connect_time'] = 0;
1606
	}
1607
	return $client;
1608
}
1609

    
1610
function openvpn_kill_client($port, $remipp) {
1611
	global $g;
1612

    
1613
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
1614
	$tcpsrv = "unix://{$g['varetc_path']}/openvpn/{$port}.sock";
1615
	$errval = null;
1616
	$errstr = null;
1617

    
1618
	/* open a tcp connection to the management port of each server */
1619
	$fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
1620
	$killed = -1;
1621
	if ($fp) {
1622
		stream_set_timeout($fp, 1);
1623
		fputs($fp, "kill {$remipp}\n");
1624
		while (!feof($fp)) {
1625
			$line = fgets($fp, 1024);
1626

    
1627
			$info = stream_get_meta_data($fp);
1628
			if ($info['timed_out']) {
1629
				break;
1630
			}
1631

    
1632
			/* parse header list line */
1633
			if (strpos($line, "INFO:") !== false) {
1634
				continue;
1635
			}
1636
			if (strpos($line, "SUCCESS") !== false) {
1637
				$killed = 0;
1638
			}
1639
			break;
1640
		}
1641
		fclose($fp);
1642
	}
1643
	return $killed;
1644
}
1645

    
1646
function openvpn_refresh_crls() {
1647
	global $g, $config;
1648

    
1649
	openvpn_create_dirs();
1650

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

    
1678
function openvpn_create_dirs() {
1679
	global $g, $config, $openvpn_tls_server_modes;
1680
	if (!is_dir("{$g['varetc_path']}/openvpn")) {
1681
		safe_mkdir("{$g['varetc_path']}/openvpn", 0750);
1682
	}
1683
	if (!is_dir("{$g['varetc_path']}/openvpn-csc")) {
1684
		safe_mkdir("{$g['varetc_path']}/openvpn-csc", 0750);
1685
	}
1686

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

    
1702
function openvpn_get_interface_ip($ip, $cidr) {
1703
	$subnet = gen_subnetv4($ip, $cidr);
1704
	$ip1 = ip_after($subnet);
1705
	$ip2 = ip_after($ip1);
1706
	return array($ip1, $ip2);
1707
}
1708

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

    
1719
function openvpn_clear_route($mode, $settings) {
1720
	if (empty($settings['tunnel_network'])) {
1721
		return;
1722
	}
1723
	list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
1724
	$mask = gen_subnet_mask($cidr);
1725
	$clear_route = false;
1726

    
1727
	switch ($settings['mode']) {
1728
		case 'shared_key':
1729
			$clear_route = true;
1730
			break;
1731
		case 'p2p_tls':
1732
		case 'p2p_shared_key':
1733
			if ($cidr == 30) {
1734
				$clear_route = true;
1735
			}
1736
			break;
1737
	}
1738

    
1739
	if ($clear_route && !empty($ip) && !empty($mask)) {
1740
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1741
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
1742
		/* XXX: Family for route? */
1743
		mwexec("/sbin/route -q delete {$ip_to_clear}");
1744
	}
1745
}
1746

    
1747
function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) {
1748
	$routes = "";
1749
	if (empty($value)) {
1750
		return "";
1751
	}
1752
	$networks = explode(',', $value);
1753

    
1754
	foreach ($networks as $network) {
1755
		if ($ipproto == "ipv4") {
1756
			$route = openvpn_gen_route_ipv4($network, $iroute);
1757
		} else {
1758
			$route = openvpn_gen_route_ipv6($network, $iroute);
1759
		}
1760

    
1761
		if ($push) {
1762
			$routes .= "push \"{$route}\"\n";
1763
		} else {
1764
			$routes .= "{$route}\n";
1765
		}
1766
	}
1767
	return $routes;
1768
}
1769

    
1770
function openvpn_gen_route_ipv4($network, $iroute = false) {
1771
	$i = ($iroute) ? "i" : "";
1772
	list($ip, $mask) = explode('/', trim($network));
1773
	$mask = gen_subnet_mask($mask);
1774
	return "{$i}route $ip $mask";
1775
}
1776

    
1777
function openvpn_gen_route_ipv6($network, $iroute = false) {
1778
	$i = ($iroute) ? "i" : "";
1779
	list($ipv6, $prefix) = explode('/', trim($network));
1780
	if (empty($prefix)) {
1781
		$prefix = "128";
1782
	}
1783
	return "{$i}route-ipv6 ${ipv6}/${prefix}";
1784
}
1785

    
1786
function openvpn_get_settings($mode, $vpnid) {
1787
	global $config;
1788

    
1789
	if (is_array($config['openvpn']['openvpn-server'])) {
1790
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
1791
			if (isset($settings['disable'])) {
1792
				continue;
1793
			}
1794

    
1795
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
1796
				return $settings;
1797
			}
1798
		}
1799
	}
1800

    
1801
	if (is_array($config['openvpn']['openvpn-client'])) {
1802
		foreach ($config['openvpn']['openvpn-client'] as $settings) {
1803
			if (isset($settings['disable'])) {
1804
				continue;
1805
			}
1806

    
1807
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
1808
				return $settings;
1809
			}
1810
		}
1811
	}
1812

    
1813
	return array();
1814
}
1815

    
1816
function openvpn_restart_by_vpnid($mode, $vpnid) {
1817
	$settings = openvpn_get_settings($mode, $vpnid);
1818
	openvpn_restart($mode, $settings);
1819
}
1820

    
1821
?>
(28-28/51)