/
openvpn.inc
2318 lines (2020 loc) · 67.3 KB
/
openvpn.inc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* openvpn.inc
*
* part of pfSense (https://www.pfsense.org)
* Copyright (c) 2006 Fernando Lemos
* Copyright (c) 2006-2013 BSD Perimeter
* Copyright (c) 2013-2016 Electric Sheep Fencing
* Copyright (c) 2014-2021 Rubicon Communications, LLC (Netgate)
* All rights reserved.
*
* This file was rewritten from scratch by Fernando Lemos but
* *MIGHT* contain code previously written by:
*
* Copyright (c) 2005 Peter Allgeyer <allgeyer_AT_web.de>
* Copyright (c) 2004 Peter Curran (peter@closeconsultants.com).
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once('config.inc');
require_once("certs.inc");
require_once('pfsense-utils.inc');
require_once("auth.inc");
global $openvpn_prots;
$openvpn_prots = array(
"UDP4" => "UDP on IPv4 only",
"UDP6" => "UDP on IPv6 only",
"TCP4" => "TCP on IPv4 only",
"TCP6" => "TCP on IPv6 only",
"UDP" => "UDP IPv4 and IPv6 on all interfaces (multihome)",
"TCP" => "TCP IPv4 and IPv6 on all interfaces (multihome)"
);
global $openvpn_dev_mode;
$openvpn_dev_mode = array(
"tun" => "tun - Layer 3 Tunnel Mode",
"tap" => "tap - Layer 2 Tap Mode"
);
global $openvpn_verbosity_level;
$openvpn_verbosity_level = array(
0 => gettext("none"),
1 => gettext("default"),
2 => "2",
3 => gettext("3 (recommended)"),
4 => "4",
5 => "5",
6 => "6",
7 => "7",
8 => "8",
9 => "9",
10 => "10",
11 => "11"
);
/*
* The User Auth mode below is disabled because
* OpenVPN erroneously requires that we provide
* a CA configuration parameter. In this mode,
* clients don't send a certificate so there is
* no need for a CA. If we require that admins
* provide one in the pfSense UI due to a bogus
* requirement imposed by OpenVPN, it could be
* considered very confusing ( I know I was ).
*
* -mgrooms
*/
global $openvpn_dh_lengths;
$openvpn_dh_lengths = array(
1024 => "1024 bit",
2048 => "2048 bit",
3072 => "3072 bit",
4096 => "4096 bit",
6144 => "6144 bit",
7680 => "7680 bit",
8192 => "8192 bit",
15360 => "15360 bit",
16384 => "16384 bit",
"none" => "ECDH Only"
);
foreach ($openvpn_dh_lengths as $idx => $dhlen) {
if (is_numeric($idx) && !file_exists("/etc/dh-parameters.{$idx}")) {
unset($openvpn_dh_lengths[$idx]);
}
}
global $openvpn_cert_depths;
$openvpn_cert_depths = array(
1 => gettext("One (Client+Server)"),
2 => gettext("Two (Client+Intermediate+Server)"),
3 => gettext("Three (Client+2xIntermediate+Server)"),
4 => gettext("Four (Client+3xIntermediate+Server)"),
5 => gettext("Five (Client+4xIntermediate+Server)")
);
global $openvpn_server_modes;
$openvpn_server_modes = array(
'p2p_tls' => gettext("Peer to Peer ( SSL/TLS )"),
'p2p_shared_key' => gettext("Peer to Peer ( Shared Key )"),
'server_tls' => gettext("Remote Access ( SSL/TLS )"),
'server_user' => gettext("Remote Access ( User Auth )"),
'server_tls_user' => gettext("Remote Access ( SSL/TLS + User Auth )"));
global $openvpn_tls_server_modes;
$openvpn_tls_server_modes = array('p2p_tls', 'server_tls', 'server_user', 'server_tls_user');
global $openvpn_client_modes;
$openvpn_client_modes = array(
'p2p_tls' => gettext("Peer to Peer ( SSL/TLS )"),
'p2p_shared_key' => gettext("Peer to Peer ( Shared Key )"));
global $openvpn_allow_compression;
$openvpn_allow_compression = array(
'asym' => gettext("Decompress incoming, do not compress outgoing (Asymmetric)"),
'no' => gettext("Refuse any non-stub compression (Most secure)"),
'yes' => gettext("Compress packets (WARNING: Potentially dangerous!)"),
);
global $openvpn_compression_modes;
$openvpn_compression_modes = array(
'' => gettext("Disable Compression [Omit Preference]"),
'none' => gettext("Disable Compression, retain compression packet framing [compress]"),
'stub' => gettext("Enable Compression (stub) [compress stub]"),
'stub-v2' => gettext("Enable Compression (stub v2) [compress stub-v2]"),
'lz4' => gettext("LZ4 Compression [compress lz4]"),
'lz4-v2' => gettext("LZ4 Compression v2 [compress lz4-v2]"),
'lzo' => gettext("LZO Compression [compress lzo, equivalent to comp-lzo yes for compatibility]"),
'noadapt' => gettext("Omit Preference, + Disable Adaptive LZO Compression [Legacy style, comp-noadapt]"),
'adaptive' => gettext("Adaptive LZO Compression [Legacy style, comp-lzo adaptive]"),
'yes' => gettext("LZO Compression [Legacy style, comp-lzo yes]"),
'no' => gettext("No LZO Compression [Legacy style, comp-lzo no]"),
);
global $openvpn_topologies;
$openvpn_topologies = array(
'subnet' => gettext("Subnet -- One IP address per client in a common subnet"),
'net30' => gettext("net30 -- Isolated /30 network per client")
);
global $openvpn_tls_modes;
$openvpn_tls_modes = array(
'auth' => gettext("TLS Authentication"),
'crypt' => gettext("TLS Encryption and Authentication")
);
global $openvpn_ping_method;
$openvpn_ping_method = array(
'keepalive' => gettext("keepalive -- Use keepalive helper to define ping configuration"),
'ping' => gettext("ping -- Define ping/ping-exit/ping-restart manually")
);
global $openvpn_default_keepalive_interval;
$openvpn_default_keepalive_interval = 10;
global $openvpn_default_keepalive_timeout;
$openvpn_default_keepalive_timeout = 60;
global $openvpn_ping_action;
$openvpn_ping_action = array(
'ping_restart' => gettext("ping-restart -- Restart OpenVPN after timeout"),
'ping_exit' => gettext("ping-exit -- Exit OpenVPN after timeout")
);
global $openvpn_exit_notify_server;
$openvpn_exit_notify_server = array(
'none' => gettext("Disabled"),
'1' => gettext("Reconnect to this server / Retry once"),
'2' => gettext("Reconnect to next server / Retry twice"),
);
global $openvpn_exit_notify_client;
$openvpn_exit_notify_client = array(
'none' => gettext("Disabled"),
);
for ($i=1; $i<=5; $i++) {
$openvpn_exit_notify_client[$i] = sprintf(gettext("Retry %dx"), $i);
}
function openvpn_build_mode_list() {
global $openvpn_server_modes;
$list = array();
foreach ($openvpn_server_modes as $name => $desc) {
$list[$name] = $desc;
}
return($list);
}
global $openvpn_interfacenames;
function convert_openvpn_interface_to_friendly_descr($if) {
global $openvpn_interfacenames;
if (!is_array($openvpn_interfacenames)) {
$openvpn_interfacenames = openvpn_build_if_list();
}
foreach($openvpn_interfacenames as $key => $value) {
list($item_if, $item_ip) = explode("|", $key);
if ($if == $item_if) {
echo "$value";
}
}
}
function openvpn_build_if_list() {
$list = array();
$interfaces = get_configured_interface_with_descr();
$viplist = get_configured_vip_list();
foreach ($viplist as $vip => $address) {
$interfaces[$vip.'|'.$address] = $address;
if (get_vip_descr($address)) {
$interfaces[$vip.'|'.$address] .= " (";
$interfaces[$vip.'|'.$address] .= get_vip_descr($address);
$interfaces[$vip.'|'.$address] .= ")";
}
}
$grouplist = return_gateway_groups_array();
foreach ($grouplist as $name => $group) {
if ($group[0]['vip'] != "") {
$vipif = $group[0]['vip'];
} else {
$vipif = $group[0]['int'];
}
$interfaces[$name] = "GW Group {$name}";
}
$interfaces['lo0'] = "Localhost";
$interfaces['any'] = "any";
foreach ($interfaces as $iface => $ifacename) {
$list[$iface] = $ifacename;
}
return($list);
}
function openvpn_build_crl_list() {
global $a_crl;
$list = array('' => 'None');
foreach ($a_crl as $crl) {
$caname = "";
$ca = lookup_ca($crl['caref']);
if ($ca) {
$caname = " (CA: {$ca['descr']})";
}
$list[$crl['refid']] = $crl['descr'] . $caname;
}
return($list);
}
function openvpn_build_cert_list($include_none = false, $prioritize_server_certs = false) {
global $a_cert;
$openvpn_compatible_certs = cert_build_list('cert', 'OpenVPN');
if ($include_none) {
$list = array('' => gettext('None (Username and/or Password required)'));
} else {
$list = array();
}
$non_server_list = array();
if ($prioritize_server_certs) {
$list[' '] = gettext("===== Server Certificates =====");
$non_server_list[' '] = gettext("===== Non-Server Certificates =====");
}
foreach ($a_cert as $cert) {
if (!array_key_exists($cert['refid'], $openvpn_compatible_certs)) {
continue;
}
$properties = array();
$propstr = "";
$ca = lookup_ca($cert['caref']);
$purpose = cert_get_purpose($cert['crt'], true);
if ($purpose['server'] == "Yes") {
$properties[] = gettext("Server: Yes");
} elseif ($prioritize_server_certs) {
$properties[] = gettext("Server: NO");
}
if ($ca) {
$properties[] = sprintf(gettext("CA: %s"), $ca['descr']);
}
if (cert_in_use($cert['refid'])) {
$properties[] = gettext("In Use");
}
if (is_cert_revoked($cert)) {
$properties[] = gettext("Revoked");
}
if (!empty($properties)) {
$propstr = " (" . implode(", ", $properties) . ")";
}
if ($prioritize_server_certs) {
if ($purpose['server'] == "Yes") {
$list[$cert['refid']] = $cert['descr'] . $propstr;
} else {
$non_server_list[$cert['refid']] = $cert['descr'] . $propstr;
}
} else {
$list[$cert['refid']] = $cert['descr'] . $propstr;
}
}
return(array('server' => $list, 'non-server' => $non_server_list));
}
function openvpn_build_bridge_list() {
$list = array();
$serverbridge_interface['none'] = "none";
$serverbridge_interface = array_merge($serverbridge_interface, get_configured_interface_with_descr());
$viplist = get_configured_vip_list();
foreach ($viplist as $vip => $address) {
$serverbridge_interface[$vip.'|'.$address] = $address;
if (get_vip_descr($address)) {
$serverbridge_interface[$vip.'|'.$address] .= " (". get_vip_descr($address) .")";
}
}
foreach ($serverbridge_interface as $iface => $ifacename) {
$list[$iface] = htmlspecialchars($ifacename);
}
return($list);
}
function openvpn_create_key() {
$fp = popen("/usr/local/sbin/openvpn --genkey secret /dev/stdout 2>/dev/null", "r");
if (!$fp) {
return false;
}
$rslt = stream_get_contents($fp);
pclose($fp);
return $rslt;
}
function openvpn_create_dhparams($bits) {
$fp = popen("/usr/bin/openssl dhparam {$bits} 2>/dev/null", "r");
if (!$fp) {
return false;
}
$rslt = stream_get_contents($fp);
pclose($fp);
return $rslt;
}
function openvpn_vpnid_used($vpnid) {
global $config;
if (is_array($config['openvpn']['openvpn-server'])) {
foreach ($config['openvpn']['openvpn-server'] as & $settings) {
if ($vpnid == $settings['vpnid']) {
return true;
}
}
}
if (is_array($config['openvpn']['openvpn-client'])) {
foreach ($config['openvpn']['openvpn-client'] as & $settings) {
if ($vpnid == $settings['vpnid']) {
return true;
}
}
}
return false;
}
function openvpn_vpnid_next() {
$vpnid = 1;
while (openvpn_vpnid_used($vpnid)) {
$vpnid++;
}
return $vpnid;
}
function openvpn_port_used($prot, $interface, $port, $curvpnid = 0) {
global $config;
$ovpn_settings = array();
if (is_array($config['openvpn']['openvpn-server'])) {
$ovpn_settings = $config['openvpn']['openvpn-server'];
}
if (is_array($config['openvpn']['openvpn-client'])) {
$ovpn_settings = array_merge($ovpn_settings,
$config['openvpn']['openvpn-client']);
}
foreach ($ovpn_settings as $settings) {
if (isset($settings['disable'])) {
continue;
}
if ($curvpnid != 0 && $curvpnid == $settings['vpnid']) {
continue;
}
/* (TCP|UDP)(4|6) does not conflict unless interface is any */
if (($interface != "any" && $settings['interface'] != "any") &&
(strlen($prot) == 4) &&
(strlen($settings['protocol']) == 4) &&
substr($prot,0,3) == substr($settings['protocol'],0,3) &&
substr($prot,3,1) != substr($settings['protocol'],3,1)) {
continue;
}
if ($port == $settings['local_port'] &&
substr($prot,0,3) == substr($settings['protocol'],0,3) &&
($interface == $settings['interface'] ||
$interface == "any" || $settings['interface'] == "any")) {
return $settings['vpnid'];
}
}
return 0;
}
function openvpn_port_next($prot, $interface = "wan") {
$port = 1194;
while (openvpn_port_used($prot, $interface, $port)) {
$port++;
}
while (openvpn_port_used($prot, "any", $port)) {
$port++;
}
return $port;
}
function openvpn_get_cipherlist() {
$ciphers = array();
$cipher_out = shell_exec('/usr/local/sbin/openvpn --show-ciphers | /usr/bin/grep \'(.*key\' | sed \'s/, TLS client\/server mode only//\'');
$cipher_lines = explode("\n", trim($cipher_out));
sort($cipher_lines);
foreach ($cipher_lines as $line) {
$words = explode(' ', $line, 2);
$ciphers[$words[0]] = "{$words[0]} {$words[1]}";
}
$ciphers["none"] = gettext("None (No Encryption)");
return $ciphers;
}
function openvpn_get_curvelist() {
global $cert_curve_compatible;
$curves = array();
$curves["none"] = gettext("Use Default");
foreach ($cert_curve_compatible['OpenVPN'] as $curve) {
$curves[$curve] = $curve;
}
return $curves;
}
function openvpn_validate_curve($curve) {
$curves = openvpn_get_curvelist();
return array_key_exists($curve, $curves);
}
/* Obtain the list of digest algorithms supported by openssl and their alternate names */
function openvpn_get_openssldigestmappings() {
$digests = array();
$digest_out = shell_exec('/usr/bin/openssl list -digest-algorithms | /usr/bin/grep "=>"');
$digest_lines = explode("\n", trim($digest_out));
sort($digest_lines);
foreach ($digest_lines as $line) {
$words = explode(' => ', $line, 2);
$digests[$words[0]] = $words[1];
}
return $digests;
}
/* Obtain the list of digest algorithms supported by openvpn */
function openvpn_get_digestlist() {
/* Grab the list from OpenSSL to check for duplicates or aliases */
$openssl_digest_mappings = openvpn_get_openssldigestmappings();
$digests = array();
$digest_out = shell_exec('/usr/local/sbin/openvpn --show-digests | /usr/bin/grep "digest size" | /usr/bin/awk \'{print $1, "(" $2 "-" $3 ")";}\'');
$digest_lines = explode("\n", trim($digest_out));
sort($digest_lines);
foreach ($digest_lines as $line) {
$words = explode(' ', $line);
/* Only add the entry if it is NOT also listed as being an alias/mapping by OpenSSL */
if (!array_key_exists($words[0], $openssl_digest_mappings)) {
$digests[$words[0]] = "{$words[0]} {$words[1]}";
}
}
$digests["none"] = gettext("None (No Authentication)");
return $digests;
}
/* Check to see if a digest name is an alias and if so, find the actual digest
* algorithm instead. Useful for upgrade code that has to translate aliased
* algorithms to their actual names.
*/
function openvpn_remap_digest($digest) {
$openssl_digest_mappings = openvpn_get_openssldigestmappings();
if (array_key_exists($digest, $openssl_digest_mappings)) {
/* Some mappings point to other mappings, keep going until we find the actual digest algorithm */
if (array_key_exists($openssl_digest_mappings[$digest], $openssl_digest_mappings)) {
return openvpn_remap_digest($openssl_digest_mappings[$digest]);
} else {
return $openssl_digest_mappings[$digest];
}
}
return $digest;
}
function openvpn_get_keydirlist() {
$keydirs = array(
'default' => gettext('Use default direction'),
'0' => gettext('Direction 0'),
'1' => gettext('Direction 1'),
'2' => gettext('Both directions'),
);
return $keydirs;
}
function openvpn_get_engines() {
$openssl_engines = array('none' => gettext('No Hardware Crypto Acceleration'));
exec("/usr/bin/openssl engine -t -c", $openssl_engine_output);
$openssl_engine_output = implode("\n", $openssl_engine_output);
$openssl_engine_output = preg_replace("/\\n\\s+/", "|", $openssl_engine_output);
$openssl_engine_output = explode("\n", $openssl_engine_output);
foreach ($openssl_engine_output as $oeo) {
$keep = true;
$details = explode("|", $oeo);
$engine = array_shift($details);
$linematch = array();
preg_match("/\((.*)\)\s(.*)/", $engine, $linematch);
foreach ($details as $dt) {
if (strpos($dt, "unavailable") !== FALSE) {
$keep = false;
}
if (strpos($dt, "available") !== FALSE) {
continue;
}
if (strpos($dt, "[") !== FALSE) {
$ciphers = trim($dt, "[]");
}
}
if (!empty($ciphers)) {
$ciphers = " - " . $ciphers;
}
if (strlen($ciphers) > 60) {
$ciphers = substr($ciphers, 0, 60) . " ... ";
}
if ($keep) {
$openssl_engines[$linematch[1]] = $linematch[2] . $ciphers;
}
}
return $openssl_engines;
}
function openvpn_get_buffer_values() {
$sendbuf_max = get_single_sysctl('net.inet.tcp.sendbuf_max');
$recvbuf_max = get_single_sysctl('net.inet.tcp.recvbuf_max');
/* Usually these two are equal, but if they are not, take whichever one is lower. */
$buffer_max = ($sendbuf_max <= $recvbuf_max) ? $sendbuf_max : $recvbuf_max;
$buffer_values = array('' => gettext('Default'));
for ($bs = 32; $bs >= 1; $bs /= 2) {
$buffer_values[$buffer_max/$bs] = format_bytes($buffer_max/$bs);
}
return $buffer_values;
}
function openvpn_validate_engine($engine) {
$engines = openvpn_get_engines();
return array_key_exists($engine, $engines);
}
function openvpn_validate_host($value, $name) {
$value = trim($value);
if (empty($value) || (!is_domain($value) && !is_ipaddr($value))) {
return sprintf(gettext("The field '%s' must contain a valid IP address or domain name."), $name);
}
return false;
}
function openvpn_validate_port($value, $name, $first_port = 0) {
$value = trim($value);
if (!is_numeric($first_port)) {
$first_port = 0;
}
if (empty($value) || !is_numeric($value) || $value < $first_port || ($value > 65535)) {
return sprintf(gettext("The field '%s' must contain a valid port, ranging from %s to 65535."), $name, $first_port);
}
return false;
}
function openvpn_validate_cidr($value, $name, $multiple = false, $ipproto = "ipv4") {
$value = trim($value);
$error = false;
if (empty($value)) {
return false;
}
$networks = explode(',', $value);
if (!$multiple && (count($networks) > 1)) {
return sprintf(gettext("The field '%1\$s' must contain a single valid %2\$s CIDR range."), $name, $ipproto);
}
foreach ($networks as $network) {
if ($ipproto == "ipv4") {
$error = !openvpn_validate_cidr_ipv4($network);
} else {
$error = !openvpn_validate_cidr_ipv6($network);
}
if ($error) {
break;
}
}
if ($error) {
return sprintf(gettext("The field '%1\$s' must contain only valid %2\$s CIDR range(s) separated by commas."), $name, $ipproto);
} else {
return false;
}
}
function openvpn_validate_cidr_ipv4($value) {
$value = trim($value);
if (!empty($value)) {
list($ip, $mask) = explode('/', $value);
if (!is_ipaddrv4($ip) or !is_numeric($mask) or ($mask > 32) or ($mask < 0)) {
return false;
}
}
return true;
}
function openvpn_validate_cidr_ipv6($value) {
$value = trim($value);
if (!empty($value)) {
list($ipv6, $prefix) = explode('/', $value);
if (empty($prefix)) {
$prefix = "128";
}
if (!is_ipaddrv6($ipv6) or !is_numeric($prefix) or ($prefix > 128) or ($prefix < 0)) {
return false;
}
}
return true;
}
function openvpn_add_dhcpopts(& $settings, & $conf) {
if (!empty($settings['dns_domain'])) {
$conf .= "push \"dhcp-option DOMAIN {$settings['dns_domain']}\"\n";
}
if (!empty($settings['dns_server1'])) {
$dnstype = (is_ipaddrv6($settings['dns_server1'])) ? "DNS6" : "DNS";
$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server1']}\"\n";
}
if (!empty($settings['dns_server2'])) {
$dnstype = (is_ipaddrv6($settings['dns_server2'])) ? "DNS6" : "DNS";
$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server2']}\"\n";
}
if (!empty($settings['dns_server3'])) {
$dnstype = (is_ipaddrv6($settings['dns_server3'])) ? "DNS6" : "DNS";
$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server3']}\"\n";
}
if (!empty($settings['dns_server4'])) {
$dnstype = (is_ipaddrv6($settings['dns_server4'])) ? "DNS6" : "DNS";
$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server4']}\"\n";
}
if (!empty($settings['push_blockoutsidedns'])) {
$conf .= "push \"block-outside-dns\"\n";
}
if (!empty($settings['push_register_dns'])) {
$conf .= "push \"register-dns\"\n";
}
if (!empty($settings['ntp_server1'])) {
$conf .= "push \"dhcp-option NTP {$settings['ntp_server1']}\"\n";
}
if (!empty($settings['ntp_server2'])) {
$conf .= "push \"dhcp-option NTP {$settings['ntp_server2']}\"\n";
}
if ($settings['netbios_enable']) {
if (!empty($settings['dhcp_nbttype']) && ($settings['dhcp_nbttype'] != 0)) {
$conf .= "push \"dhcp-option NBT {$settings['dhcp_nbttype']}\"\n";
}
if (!empty($settings['dhcp_nbtscope'])) {
$conf .= "push \"dhcp-option NBS {$settings['dhcp_nbtscope']}\"\n";
}
if (!empty($settings['wins_server1'])) {
$conf .= "push \"dhcp-option WINS {$settings['wins_server1']}\"\n";
}
if (!empty($settings['wins_server2'])) {
$conf .= "push \"dhcp-option WINS {$settings['wins_server2']}\"\n";
}
if (!empty($settings['nbdd_server1'])) {
$conf .= "push \"dhcp-option NBDD {$settings['nbdd_server1']}\"\n";
}
}
if ($settings['gwredir']) {
$conf .= "push \"redirect-gateway def1\"\n";
}
if ($settings['gwredir6']) {
$conf .= "push \"redirect-gateway ipv6\"\n";
}
}
function openvpn_add_custom(& $settings, & $conf) {
if ($settings['custom_options']) {
$options = explode(';', $settings['custom_options']);
if (is_array($options)) {
foreach ($options as $option) {
$conf .= "$option\n";
}
} else {
$conf .= "{$settings['custom_options']}\n";
}
}
}
function openvpn_add_keyfile(& $data, & $conf, $mode_id, $directive, $opt = "") {
global $g;
$fpath = "{$g['openvpn_base']}/{$mode_id}/{$directive}";
openvpn_create_dirs();
file_put_contents($fpath, base64_decode($data));
//chown($fpath, 'nobody');
//chgrp($fpath, 'nobody');
@chmod($fpath, 0600);
$conf .= "{$directive} {$fpath} {$opt}\n";
}
function openvpn_reconfigure($mode, $settings) {
global $g, $config, $openvpn_tls_server_modes, $openvpn_dh_lengths, $openvpn_default_keepalive_interval, $openvpn_default_keepalive_timeout;
if (empty($settings)) {
return;
}
if (isset($settings['disable'])) {
return;
}
openvpn_create_dirs();
/*
* NOTE: Deleting tap devices causes spontaneous reboots. Instead,
* we use a vpnid number which is allocated for a particular client
* or server configuration. ( see openvpn_vpnid_next() )
*/
$vpnid = $settings['vpnid'];
$mode_id = $mode.$vpnid;
if (isset($settings['dev_mode'])) {
$tunname = "{$settings['dev_mode']}{$vpnid}";
} else {
/* defaults to tun */
$tunname = "tun{$vpnid}";
$settings['dev_mode'] = "tun";
}
if ($mode == "server") {
$devname = "ovpns{$vpnid}";
} else {
$devname = "ovpnc{$vpnid}";
}
/* is our device already configured */
if (!does_interface_exist($devname)) {
/* create the tap device if required */
if (!file_exists("/dev/{$tunname}")) {
exec("/sbin/ifconfig " . escapeshellarg($tunname) . " create");
}
/* rename the device */
mwexec("/sbin/ifconfig " . escapeshellarg($tunname) . " name " . escapeshellarg($devname));
/* add the device to the openvpn group and make sure it's UP*/
mwexec("/sbin/ifconfig " . escapeshellarg($devname) . " group openvpn up");
$ifname = convert_real_interface_to_friendly_interface_name($devname);
$grouptmp = link_interface_to_group($ifname);
if (!empty($grouptmp)) {
array_walk($grouptmp, 'interface_group_add_member');
}
unset($grouptmp, $ifname);
}
$pfile = $g['varrun_path'] . "/openvpn_{$mode_id}.pid";
$proto = strtolower($settings['protocol']);
if (substr($settings['protocol'], 0, 3) == "TCP") {
$proto = "{$proto}-{$mode}";
}
$dev_mode = $settings['dev_mode'];
$fbcipher = $settings['data_ciphers_fallback'];
// OpenVPN defaults to SHA1, so use it when unset to maintain compatibility.
$digest = !empty($settings['digest']) ? $settings['digest'] : "SHA1";
$interface = get_failover_interface($settings['interface']);
// The IP address in the settings can be an IPv4 or IPv6 address associated with the interface
$ipaddr = $settings['ipaddr'];
// If a specific ip address (VIP) is requested, use it.
// Otherwise, if a specific interface is requested, use it
// If "any" interface was selected, local directive will be omitted.
if (is_ipaddrv4($ipaddr)) {
$iface_ip = $ipaddr;
} elseif (!empty($interface) && strcmp($interface, "any")) {
$iface_ip=get_interface_ip($interface);
}
if (is_ipaddrv6($ipaddr)) {
$iface_ipv6 = $ipaddr;
} elseif (!empty($interface) && strcmp($interface, "any")) {
/* get correct interface name for 6RD/6to4 interfaces
* see https://redmine.pfsense.org/issues/11674 */
if (is_stf_interface($settings['interface'])) {
$iface_ipv6=get_interface_ipv6($settings['interface']);
} else {
$iface_ipv6=get_interface_ipv6($interface);
}
}
$conf = "dev {$devname}\n";
if (isset($settings['verbosity_level'])) {
$conf .= "verb {$settings['verbosity_level']}\n";
}
$conf .= "dev-type {$settings['dev_mode']}\n";
$conf .= "dev-node /dev/{$tunname}\n";
$conf .= "writepid {$pfile}\n";
$conf .= "#user nobody\n";
$conf .= "#group nobody\n";
$conf .= "script-security 3\n";
$conf .= "daemon\n";
if (!empty($settings['inactive_seconds'])) {
$conf .= "inactive {$settings['inactive_seconds']}\n";
}
if (!empty($settings['ping_method']) &&
$settings['ping_method'] == 'ping') {
$conf .= "ping {$settings['ping_seconds']}\n";
if (!empty($settings['ping_push'])) {
$conf .= "push \"ping {$settings['ping_seconds']}\"\n";
}
$action = str_replace("_", "-", $settings['ping_action']);
$conf .= "{$action} {$settings['ping_action_seconds']}\n";
if (!empty($settings['ping_action_push'])) {
$conf .= "push \"{$action} " .
"{$settings['ping_action_seconds']}\"\n";
}
} else {
$conf .= "keepalive " .
($settings['keepalive_interval']
?: $openvpn_default_keepalive_interval) . " " .
($settings['keepalive_timeout']
?: $openvpn_default_keepalive_timeout) . "\n";
}
$conf .= "ping-timer-rem\n";
$conf .= "persist-tun\n";
$conf .= "persist-key\n";
$conf .= "proto {$proto}\n";
$conf .= "auth {$digest}\n";
if ($settings['dns_add']) {
$conf .= "up /usr/local/sbin/ovpn-dnslinkup\n";
} else {
$conf .= "up /usr/local/sbin/ovpn-linkup\n";
}
$conf .= "down /usr/local/sbin/ovpn-linkdown\n";
if (file_exists("/usr/local/sbin/openvpn.attributes.sh")) {
switch ($settings['mode']) {
case 'server_user':
case 'server_tls_user':
case 'server_tls':
$conf .= "client-connect /usr/local/sbin/openvpn.attributes.sh\n";
$conf .= "client-disconnect /usr/local/sbin/openvpn.attributes.sh\n";
break;
}
}
if ($settings['dev_mode'] === 'tun' && isset($config['unbound']['enable']) && isset($config['unbound']['regovpnclients'])) {
if (($settings['mode'] == 'server_tls') || ($settings['mode'] == 'server_tls_user') ||
(($settings['mode'] == 'server_user') && ($settings['username_as_common_name'] == 'enabled'))) {
$domain = !empty($settings['dns_domain']) ? $settings['dns_domain'] : $config['system']['domain'];
if (is_domain($domain)) {
$conf .= "learn-address \"/usr/local/sbin/openvpn.learn-address.sh $domain\"\n";
}
}
}
/*
* When binding specific address, wait cases where interface is in
* tentative state otherwise it will fail
*/
$wait_tentative = false;
/* Determine the local IP to use - and make sure it matches with the selected protocol. */
switch ($settings['protocol']) {
case 'UDP':
case 'TCP':
$conf .= "multihome\n";
break;
case 'UDP4':
case 'TCP4':
if (is_ipaddrv4($iface_ip)) {
$conf .= "local {$iface_ip}\n";
}
if ($settings['interface'] == "any") {
$conf .= "multihome\n";
}
break;
case 'UDP6':
case 'TCP6':
if (is_ipaddrv6($iface_ipv6)) {
$conf .= "local {$iface_ipv6}\n";
$wait_tentative = true;
}
if ($settings['interface'] == "any") {
$conf .= "multihome\n";
}
break;
default:
}
if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none")) {
$conf .= "engine {$settings['engine']}\n";
}
// server specific settings
if ($mode == 'server') {
list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
$mask = gen_subnet_mask($cidr);
// configure tls modes
switch ($settings['mode']) {
case 'p2p_tls':
case 'server_tls':
case 'server_user':
case 'server_tls_user':
$conf .= "tls-server\n";
break;
}
// configure p2p/server modes
switch ($settings['mode']) {
case 'p2p_tls':
// If the CIDR is less than a /30, OpenVPN will complain if you try to
// use the server directive. It works for a single client without it.
// See ticket #1417
if ((!empty($ip) && !empty($mask)) ||
(!empty($ipv6) && !empty($prefix))) {
$add_ccd = false;
if (is_ipaddr($ip) && ($cidr < 30)) {