Project

General

Profile

Download (50.7 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 Electric Sheep Fencing, LLC
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
	'no' => gettext("Disabled - No Compression"),
104
	'adaptive' => gettext("Enabled with Adaptive Compression"),
105
	'yes' => gettext("Enabled without Adaptive Compression"));
106

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

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

    
117
	$list = array();
118

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

    
123
	return($list);
124
}
125

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

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

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

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

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

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

    
158
	return($list);
159
}
160

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

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

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

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

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

    
177
	return($list);
178
}
179

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

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

    
189
	$non_server_list = array();
190

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

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

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

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

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

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

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

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

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

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

    
253
	return($list);
254
}
255

    
256
function openvpn_create_key() {
257

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

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

    
266
	return $rslt;
267
}
268

    
269
function openvpn_create_dhparams($bits) {
270

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

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

    
279
	return $rslt;
280
}
281

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

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

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

    
301
	return false;
302
}
303

    
304
function openvpn_vpnid_next() {
305

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

    
311
	return $vpnid;
312
}
313

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

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

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

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

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

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

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

    
351
	return 0;
352
}
353

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

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

    
364
	return $port;
365
}
366

    
367
function openvpn_get_cipherlist() {
368

    
369
	$ciphers = array();
370
	$cipher_out = shell_exec('/usr/local/sbin/openvpn --show-ciphers | /usr/bin/grep "default key" | /usr/bin/awk \'{print $1, "(" $2 "-" $3 ")";}\'');
371
	$cipher_lines = explode("\n", trim($cipher_out));
372
	sort($cipher_lines);
373
	foreach ($cipher_lines as $line) {
374
		$words = explode(' ', $line);
375
		$ciphers[$words[0]] = "{$words[0]} {$words[1]}";
376
	}
377
	$ciphers["none"] = gettext("None (No Encryption)");
378
	return $ciphers;
379
}
380

    
381
function openvpn_get_digestlist() {
382

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
527
	if (!empty($settings['push_register_dns'])) {
528
		$conf .= "push \"register-dns\"\n";
529
	}
530

    
531
	if (!empty($settings['ntp_server1'])) {
532
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server1']}\"\n";
533
	}
534
	if (!empty($settings['ntp_server2'])) {
535
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server2']}\"\n";
536
	}
537

    
538
	if ($settings['netbios_enable']) {
539

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

    
547
		if (!empty($settings['wins_server1'])) {
548
			$conf .= "push \"dhcp-option WINS {$settings['wins_server1']}\"\n";
549
		}
550
		if (!empty($settings['wins_server2'])) {
551
			$conf .= "push \"dhcp-option WINS {$settings['wins_server2']}\"\n";
552
		}
553

    
554
		if (!empty($settings['nbdd_server1'])) {
555
			$conf .= "push \"dhcp-option NBDD {$settings['nbdd_server1']}\"\n";
556
		}
557
	}
558

    
559
	if ($settings['gwredir']) {
560
		$conf .= "push \"redirect-gateway def1\"\n";
561
	}
562
}
563

    
564
function openvpn_add_custom(& $settings, & $conf) {
565

    
566
	if ($settings['custom_options']) {
567

    
568
		$options = explode(';', $settings['custom_options']);
569

    
570
		if (is_array($options)) {
571
			foreach ($options as $option) {
572
				$conf .= "$option\n";
573
			}
574
		} else {
575
			$conf .= "{$settings['custom_options']}\n";
576
		}
577
	}
578
}
579

    
580
function openvpn_add_keyfile(& $data, & $conf, $mode_id, $directive, $opt = "") {
581
	global $g;
582

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

    
590
	$conf .= "{$directive} {$fpath} {$opt}\n";
591
}
592

    
593
function openvpn_reconfigure($mode, $settings) {
594
	global $g, $config, $openvpn_tls_server_modes;
595

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

    
609
	$vpnid = $settings['vpnid'];
610
	$mode_id = $mode.$vpnid;
611

    
612
	if (isset($settings['dev_mode'])) {
613
		$tunname = "{$settings['dev_mode']}{$vpnid}";
614
	} else {
615
		/* defaults to tun */
616
		$tunname = "tun{$vpnid}";
617
		$settings['dev_mode'] = "tun";
618
	}
619

    
620
	if ($mode == "server") {
621
		$devname = "ovpns{$vpnid}";
622
	} else {
623
		$devname = "ovpnc{$vpnid}";
624
	}
625

    
626
	/* is our device already configured */
627
	if (!does_interface_exist($devname)) {
628

    
629
		/* create the tap device if required */
630
		if (!file_exists("/dev/{$tunname}")) {
631
			exec("/sbin/ifconfig " . escapeshellarg($tunname) . " create");
632
		}
633

    
634
		/* rename the device */
635
		mwexec("/sbin/ifconfig " . escapeshellarg($tunname) . " name " . escapeshellarg($devname));
636

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

    
640
		$ifname = convert_real_interface_to_friendly_interface_name($devname);
641
		$grouptmp = link_interface_to_group($ifname);
642
		if (!empty($grouptmp)) {
643
			array_walk($grouptmp, 'interface_group_add_member');
644
		}
645
		unset($grouptmp, $ifname);
646
	}
647

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

    
658
	$interface = get_failover_interface($settings['interface']);
659
	// The IP address in the settings can be an IPv4 or IPv6 address associated with the interface
660
	$ipaddr = $settings['ipaddr'];
661

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

    
680

    
681
	$conf = "dev {$devname}\n";
682
	if (isset($settings['verbosity_level'])) {
683
		$conf .= "verb {$settings['verbosity_level']}\n";
684
	}
685

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

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

    
726
	if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none")) {
727
		$conf .= "engine {$settings['engine']}\n";
728
	}
729

    
730
	// server specific settings
731
	if ($mode == 'server') {
732

    
733
		list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
734
		list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
735
		$mask = gen_subnet_mask($cidr);
736

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

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

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

    
838
		// The local port to listen on
839
		$conf .= "lport {$settings['local_port']}\n";
840

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

    
846
		if ($settings['maxclients']) {
847
			$conf .= "max-clients {$settings['maxclients']}\n";
848
		}
849

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

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

    
874
	// client specific settings
875

    
876
	if ($mode == 'client') {
877

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

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

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

    
901
		// The remote server
902
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']}\n";
903

    
904
		if (!empty($settings['use_shaper'])) {
905
			$conf .= "shaper {$settings['use_shaper']}\n";
906
		}
907

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

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

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

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

    
959
	// Add a remote network route if set, and only for p2p modes.
960
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE)) {
961
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false);
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_networkv6'], "", true, "ipv6") === FALSE)) {
965
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false);
966
	}
967

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

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

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

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

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

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

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

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

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

    
1052
	openvpn_add_custom($settings, $conf);
1053

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

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

    
1072
	$vpnid = $settings['vpnid'];
1073
	$mode_id = $mode.$vpnid;
1074

    
1075
	/* kill the process if running */
1076
	$pfile = $g['varrun_path']."/openvpn_{$mode_id}.pid";
1077
	if (file_exists($pfile)) {
1078

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

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

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

    
1099
	if (isset($settings['disable'])) {
1100
		return;
1101
	}
1102

    
1103
	/* Do not start a client if we are a CARP backup on this vip! */
1104
	if (($mode == "client") && (strstr($settings['interface'], "_vip") && get_carp_interface_status($settings['interface']) != "MASTER")) {
1105
		return;
1106
	}
1107

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

    
1117
	/* start the new process */
1118
	$fpath = $g['varetc_path']."/openvpn/{$mode_id}.conf";
1119
	openvpn_clear_route($mode, $settings);
1120
	mwexec_bg("/usr/local/sbin/openvpn --config " . escapeshellarg($fpath));
1121

    
1122
	if (!platform_booting()) {
1123
		send_event("filter reload");
1124
	}
1125
}
1126

    
1127
function openvpn_delete($mode, & $settings) {
1128
	global $g, $config;
1129

    
1130
	$vpnid = $settings['vpnid'];
1131
	$mode_id = $mode.$vpnid;
1132

    
1133
	if (isset($settings['dev_mode'])) {
1134
		$tunname = "{$settings['dev_mode']}{$vpnid}";
1135
	} else {
1136
		/* defaults to tun */
1137
		$tunname = "tun{$vpnid}";
1138
	}
1139

    
1140
	if ($mode == "server") {
1141
		$devname = "ovpns{$vpnid}";
1142
	} else {
1143
		$devname = "ovpnc{$vpnid}";
1144
	}
1145

    
1146
	/* kill the process if running */
1147
	$pfile = "{$g['varrun_path']}/openvpn_{$mode_id}.pid";
1148
	if (file_exists($pfile)) {
1149

    
1150
		/* read the pid file */
1151
		$pid = trim(file_get_contents($pfile));
1152
		unlink($pfile);
1153

    
1154
		/* send a term signal to the process */
1155
		posix_kill($pid, SIGTERM);
1156
	}
1157

    
1158
	/* remove the device from the openvpn group */
1159
	mwexec("/sbin/ifconfig " . escapeshellarg($devname) . " -group openvpn");
1160

    
1161
	/* restore the original adapter name */
1162
	mwexec("/sbin/ifconfig " . escapeshellarg($devname) . " name " . escapeshellarg($tunname));
1163

    
1164
	/* remove the configuration files */
1165
	@array_map('unlink', glob("{$g['varetc_path']}/openvpn/{$mode_id}.*"));
1166
}
1167

    
1168
function openvpn_resync_csc(& $settings) {
1169
	global $g, $config, $openvpn_tls_server_modes;
1170

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

    
1173
	if (isset($settings['disable'])) {
1174
		openvpn_delete_csc($settings);
1175
		return;
1176
	}
1177
	openvpn_create_dirs();
1178

    
1179
	if (empty($settings['server_list'])) {
1180
		$csc_server_list = array();
1181
	} else {
1182
		$csc_server_list = explode(",", $settings['server_list']);
1183
	}
1184

    
1185
	$conf = '';
1186
	if ($settings['block']) {
1187
		$conf .= "disable\n";
1188
	}
1189

    
1190
	if ($settings['push_reset']) {
1191
		$conf .= "push-reset\n";
1192
	}
1193

    
1194
	if ($settings['local_network']) {
1195
		$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1196
	}
1197
	if ($settings['local_networkv6']) {
1198
		$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1199
	}
1200

    
1201
	// Add a remote network iroute if set
1202
	if (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE) {
1203
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false, true);
1204
	}
1205
	// Add a remote network iroute if set
1206
	if (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE) {
1207
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false, true);
1208
	}
1209

    
1210
	openvpn_add_dhcpopts($settings, $conf);
1211

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

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

    
1245
function openvpn_resync_csc_all() {
1246
	global $config;
1247
	if (is_array($config['openvpn']['openvpn-csc'])) {
1248
		foreach ($config['openvpn']['openvpn-csc'] as & $settings) {
1249
			openvpn_resync_csc($settings);
1250
		}
1251
	}
1252
}
1253

    
1254
function openvpn_delete_csc(& $settings) {
1255
	global $g, $config, $openvpn_tls_server_modes;
1256
	$csc_base_path = "{$g['varetc_path']}/openvpn-csc";
1257
	if (empty($settings['server_list'])) {
1258
		$csc_server_list = array();
1259
	} else {
1260
		$csc_server_list = explode(",", $settings['server_list']);
1261
	}
1262

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

    
1279
// Resync the configuration and restart the VPN
1280
function openvpn_resync($mode, $settings) {
1281
	openvpn_reconfigure($mode, $settings);
1282
	openvpn_restart($mode, $settings);
1283
}
1284

    
1285
// Resync and restart all VPNs
1286
function openvpn_resync_all($interface = "") {
1287
	global $g, $config;
1288

    
1289
	openvpn_create_dirs();
1290

    
1291
	if (!is_array($config['openvpn'])) {
1292
		$config['openvpn'] = array();
1293
	}
1294

    
1295
/*
1296
	if (!$config['openvpn']['dh-parameters']) {
1297
		echo "Configuring OpenVPN Parameters ...\n";
1298
		$dh_parameters = openvpn_create_dhparams(1024);
1299
		$dh_parameters = base64_encode($dh_parameters);
1300
		$config['openvpn']['dh-parameters'] = $dh_parameters;
1301
		write_config("OpenVPN DH parameters");
1302
	}
1303

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

    
1317
	if (is_array($config['openvpn']['openvpn-server'])) {
1318
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1319
			if ($interface <> "" && $interface != $settings['interface']) {
1320
				continue;
1321
			}
1322
			openvpn_resync('server', $settings);
1323
		}
1324
	}
1325

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

    
1335
	openvpn_resync_csc_all();
1336

    
1337
}
1338

    
1339
// Resync and restart all VPNs using a gateway group.
1340
function openvpn_resync_gwgroup($gwgroupname = "") {
1341
	global $g, $config;
1342

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

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

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

    
1364
	} else {
1365
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1366
	}
1367
}
1368

    
1369
function openvpn_get_active_servers($type="multipoint") {
1370
	global $config, $g;
1371

    
1372
	$servers = array();
1373
	if (is_array($config['openvpn']['openvpn-server'])) {
1374
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1375
			if (empty($settings) || isset($settings['disable'])) {
1376
				continue;
1377
			}
1378

    
1379
			$prot = $settings['protocol'];
1380
			$port = $settings['local_port'];
1381

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

    
1396
			if ((($server['mode'] == "p2p_shared_key") || ($sm >= 30)) && ($type == "p2p")) {
1397
				$servers[] = openvpn_get_client_status($server, $socket);
1398
			} elseif (($server['mode'] != "p2p_shared_key") && ($type == "multipoint") && ($sm < 30)) {
1399
				$servers[] = openvpn_get_server_status($server, $socket);
1400
			}
1401
		}
1402
	}
1403
	return $servers;
1404
}
1405

    
1406
function openvpn_get_server_status($server, $socket) {
1407
	$errval = null;
1408
	$errstr = null;
1409
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1410
	if ($fp) {
1411
		stream_set_timeout($fp, 1);
1412

    
1413
		/* send our status request */
1414
		fputs($fp, "status 2\n");
1415

    
1416
		/* recv all response lines */
1417
		while (!feof($fp)) {
1418

    
1419
			/* read the next line */
1420
			$line = fgets($fp, 1024);
1421

    
1422
			$info = stream_get_meta_data($fp);
1423
			if ($info['timed_out']) {
1424
				break;
1425
			}
1426

    
1427
			/* parse header list line */
1428
			if (strstr($line, "HEADER")) {
1429
				continue;
1430
			}
1431

    
1432
			/* parse end of output line */
1433
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1434
				break;
1435
			}
1436

    
1437
			/* parse client list line */
1438
			if (strstr($line, "CLIENT_LIST")) {
1439
				$list = explode(",", $line);
1440
				$conn = array();
1441
				$conn['common_name'] = $list[1];
1442
				$conn['remote_host'] = $list[2];
1443
				$conn['virtual_addr'] = $list[3];
1444
				$conn['bytes_recv'] = $list[4];
1445
				$conn['bytes_sent'] = $list[5];
1446
				$conn['connect_time'] = $list[6];
1447
				$server['conns'][] = $conn;
1448
			}
1449
			/* parse routing table lines */
1450
			if (strstr($line, "ROUTING_TABLE")) {
1451
				$list = explode(",", $line);
1452
				$conn = array();
1453
				$conn['virtual_addr'] = $list[1];
1454
				$conn['common_name'] = $list[2];
1455
				$conn['remote_host'] = $list[3];
1456
				$conn['last_time'] = $list[4];
1457
				$server['routes'][] = $conn;
1458
			}
1459
		}
1460

    
1461
		/* cleanup */
1462
		fclose($fp);
1463
	} else {
1464
		$conn = array();
1465
		$conn['common_name'] = "[error]";
1466
		$conn['remote_host'] = gettext("Unable to contact daemon");
1467
		$conn['virtual_addr'] = gettext("Service not running?");
1468
		$conn['bytes_recv'] = 0;
1469
		$conn['bytes_sent'] = 0;
1470
		$conn['connect_time'] = 0;
1471
		$server['conns'][] = $conn;
1472
	}
1473
	return $server;
1474
}
1475

    
1476
function openvpn_get_active_clients() {
1477
	global $config, $g;
1478

    
1479
	$clients = array();
1480
	if (is_array($config['openvpn']['openvpn-client'])) {
1481
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1482

    
1483
			if (empty($settings) || isset($settings['disable'])) {
1484
				continue;
1485
			}
1486

    
1487
			$prot = $settings['protocol'];
1488
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
1489

    
1490
			$client = array();
1491
			$client['port'] = $settings['local_port'];
1492
			if ($settings['description']) {
1493
				$client['name'] = "{$settings['description']} {$prot}{$port}";
1494
			} else {
1495
				$client['name'] = "Client {$prot}{$port}";
1496
			}
1497

    
1498
			$client['vpnid'] = $settings['vpnid'];
1499
			$client['mgmt'] = "client{$client['vpnid']}";
1500
			$socket = "unix://{$g['varetc_path']}/openvpn/{$client['mgmt']}.sock";
1501
			$client['status']="down";
1502

    
1503
			$clients[] = openvpn_get_client_status($client, $socket);
1504
		}
1505
	}
1506
	return $clients;
1507
}
1508

    
1509
function openvpn_get_client_status($client, $socket) {
1510
	$errval = null;
1511
	$errstr = null;
1512
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1513
	if ($fp) {
1514
		stream_set_timeout($fp, 1);
1515
		/* send our status request */
1516
		fputs($fp, "state 1\n");
1517

    
1518
		/* recv all response lines */
1519
		while (!feof($fp)) {
1520
			/* read the next line */
1521
			$line = fgets($fp, 1024);
1522

    
1523
			$info = stream_get_meta_data($fp);
1524
			if ($info['timed_out']) {
1525
				break;
1526
			}
1527

    
1528
			/* Get the client state */
1529
			if (strstr($line, "CONNECTED")) {
1530
				$client['status'] = "up";
1531
				$list = explode(",", $line);
1532

    
1533
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1534
				$client['virtual_addr'] = $list[3];
1535
				$client['remote_host'] = $list[4];
1536
			}
1537
			if (strstr($line, "CONNECTING")) {
1538
				$client['status'] = "connecting";
1539
			}
1540
			if (strstr($line, "ASSIGN_IP")) {
1541
				$client['status'] = "waiting";
1542
				$list = explode(",", $line);
1543

    
1544
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1545
				$client['virtual_addr'] = $list[3];
1546
			}
1547
			if (strstr($line, "RECONNECTING")) {
1548
				$client['status'] = "reconnecting";
1549
				$list = explode(",", $line);
1550

    
1551
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1552
				$client['status'] .= "; " . $list[2];
1553
			}
1554
			/* parse end of output line */
1555
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1556
				break;
1557
			}
1558
		}
1559

    
1560
		/* If up, get read/write stats */
1561
		if (strcmp($client['status'], "up") == 0) {
1562
			fputs($fp, "status 2\n");
1563
			/* recv all response lines */
1564
			while (!feof($fp)) {
1565
				/* read the next line */
1566
				$line = fgets($fp, 1024);
1567

    
1568
				$info = stream_get_meta_data($fp);
1569
				if ($info['timed_out']) {
1570
					break;
1571
				}
1572

    
1573
				if (strstr($line, "TCP/UDP read bytes")) {
1574
					$list = explode(",", $line);
1575
					$client['bytes_recv'] = $list[1];
1576
				}
1577

    
1578
				if (strstr($line, "TCP/UDP write bytes")) {
1579
					$list = explode(",", $line);
1580
					$client['bytes_sent'] = $list[1];
1581
				}
1582

    
1583
				/* parse end of output line */
1584
				if (strstr($line, "END")) {
1585
					break;
1586
				}
1587
			}
1588
		}
1589

    
1590
		fclose($fp);
1591

    
1592
	} else {
1593
		$client['remote_host'] = gettext("Unable to contact daemon");
1594
		$client['virtual_addr'] = gettext("Service not running?");
1595
		$client['bytes_recv'] = 0;
1596
		$client['bytes_sent'] = 0;
1597
		$client['connect_time'] = 0;
1598
	}
1599
	return $client;
1600
}
1601

    
1602
function openvpn_kill_client($port, $remipp) {
1603
	global $g;
1604

    
1605
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
1606
	$tcpsrv = "unix://{$g['varetc_path']}/openvpn/{$port}.sock";
1607
	$errval = null;
1608
	$errstr = null;
1609

    
1610
	/* open a tcp connection to the management port of each server */
1611
	$fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
1612
	$killed = -1;
1613
	if ($fp) {
1614
		stream_set_timeout($fp, 1);
1615
		fputs($fp, "kill {$remipp}\n");
1616
		while (!feof($fp)) {
1617
			$line = fgets($fp, 1024);
1618

    
1619
			$info = stream_get_meta_data($fp);
1620
			if ($info['timed_out']) {
1621
				break;
1622
			}
1623

    
1624
			/* parse header list line */
1625
			if (strpos($line, "INFO:") !== false) {
1626
				continue;
1627
			}
1628
			if (strpos($line, "SUCCESS") !== false) {
1629
				$killed = 0;
1630
			}
1631
			break;
1632
		}
1633
		fclose($fp);
1634
	}
1635
	return $killed;
1636
}
1637

    
1638
function openvpn_refresh_crls() {
1639
	global $g, $config;
1640

    
1641
	openvpn_create_dirs();
1642

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

    
1670
function openvpn_create_dirs() {
1671
	global $g, $config, $openvpn_tls_server_modes;
1672
	if (!is_dir("{$g['varetc_path']}/openvpn")) {
1673
		safe_mkdir("{$g['varetc_path']}/openvpn", 0750);
1674
	}
1675
	if (!is_dir("{$g['varetc_path']}/openvpn-csc")) {
1676
		safe_mkdir("{$g['varetc_path']}/openvpn-csc", 0750);
1677
	}
1678

    
1679
	/* Check for enabled servers and create server-specific CSC dirs */
1680
	if (is_array($config['openvpn']['openvpn-server'])) {
1681
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
1682
			if (isset($settings['disable'])) {
1683
				continue;
1684
			}
1685
			if (in_array($settings['mode'], $openvpn_tls_server_modes)) {
1686
				if ($settings['vpnid']) {
1687
					safe_mkdir("{$g['varetc_path']}/openvpn-csc/server{$settings['vpnid']}");
1688
				}
1689
			}
1690
		}
1691
	}
1692
}
1693

    
1694
function openvpn_get_interface_ip($ip, $cidr) {
1695
	$subnet = gen_subnetv4($ip, $cidr);
1696
	$ip1 = ip_after($subnet);
1697
	$ip2 = ip_after($ip1);
1698
	return array($ip1, $ip2);
1699
}
1700

    
1701
function openvpn_get_interface_ipv6($ipv6, $prefix) {
1702
	$basev6 = gen_subnetv6($ipv6, $prefix);
1703
	// Is there a better way to do this math?
1704
	$ipv6_arr = explode(':', $basev6);
1705
	$last = hexdec(array_pop($ipv6_arr));
1706
	$ipv6_1 = Net_IPv6::compress(Net_IPv6::uncompress(implode(':', $ipv6_arr) . ':' . dechex($last + 1)));
1707
	$ipv6_2 = Net_IPv6::compress(Net_IPv6::uncompress(implode(':', $ipv6_arr) . ':' . dechex($last + 2)));
1708
	return array($ipv6_1, $ipv6_2);
1709
}
1710

    
1711
function openvpn_clear_route($mode, $settings) {
1712
	if (empty($settings['tunnel_network'])) {
1713
		return;
1714
	}
1715
	list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
1716
	$mask = gen_subnet_mask($cidr);
1717
	$clear_route = false;
1718

    
1719
	switch ($settings['mode']) {
1720
		case 'shared_key':
1721
			$clear_route = true;
1722
			break;
1723
		case 'p2p_tls':
1724
		case 'p2p_shared_key':
1725
			if ($cidr == 30) {
1726
				$clear_route = true;
1727
			}
1728
			break;
1729
	}
1730

    
1731
	if ($clear_route && !empty($ip) && !empty($mask)) {
1732
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1733
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
1734
		/* XXX: Family for route? */
1735
		mwexec("/sbin/route -q delete {$ip_to_clear}");
1736
	}
1737
}
1738

    
1739
function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) {
1740
	$routes = "";
1741
	if (empty($value)) {
1742
		return "";
1743
	}
1744
	$networks = explode(',', $value);
1745

    
1746
	foreach ($networks as $network) {
1747
		if ($ipproto == "ipv4") {
1748
			$route = openvpn_gen_route_ipv4($network, $iroute);
1749
		} else {
1750
			$route = openvpn_gen_route_ipv6($network, $iroute);
1751
		}
1752

    
1753
		if ($push) {
1754
			$routes .= "push \"{$route}\"\n";
1755
		} else {
1756
			$routes .= "{$route}\n";
1757
		}
1758
	}
1759
	return $routes;
1760
}
1761

    
1762
function openvpn_gen_route_ipv4($network, $iroute = false) {
1763
	$i = ($iroute) ? "i" : "";
1764
	list($ip, $mask) = explode('/', trim($network));
1765
	$mask = gen_subnet_mask($mask);
1766
	return "{$i}route $ip $mask";
1767
}
1768

    
1769
function openvpn_gen_route_ipv6($network, $iroute = false) {
1770
	$i = ($iroute) ? "i" : "";
1771
	list($ipv6, $prefix) = explode('/', trim($network));
1772
	if (empty($prefix)) {
1773
		$prefix = "128";
1774
	}
1775
	return "{$i}route-ipv6 ${ipv6}/${prefix}";
1776
}
1777

    
1778
function openvpn_get_settings($mode, $vpnid) {
1779
	global $config;
1780

    
1781
	if (is_array($config['openvpn']['openvpn-server'])) {
1782
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
1783
			if (isset($settings['disable'])) {
1784
				continue;
1785
			}
1786

    
1787
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
1788
				return $settings;
1789
			}
1790
		}
1791
	}
1792

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

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

    
1805
	return array();
1806
}
1807

    
1808
function openvpn_restart_by_vpnid($mode, $vpnid) {
1809
	$settings = openvpn_get_settings($mode, $vpnid);
1810
	openvpn_restart($mode, $settings);
1811
}
1812

    
1813
?>
(37-37/65)