summaryrefslogtreecommitdiff
path: root/scripts/vpn-config.pl
blob: 0369f7620f319224f59607d670c05b27c718cd89 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
#!/usr/bin/perl -w
#
# Module: vpn-config.pl
#
# **** License ****
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# This code was originally developed by Vyatta, Inc.
# Portions created by Vyatta are Copyright (C) 2006, 2007, 2008, 2009 Vyatta, Inc.
# All Rights Reserved.
#
# Authors: Justin Fletcher, Marat Nepomnyashy
# Date: 2007
# Description: Start Openswan VPN based on verified configuration
#
# **** End License ****
#

use strict;
use lib "/opt/vyatta/share/perl5";

use constant IKELIFETIME_DEFAULT => 28800;    # 8 hours
use constant ESPLIFETIME_DEFAULT => 3600;     # 1 hour
use constant REKEYMARGIN_DEFAULT => 540;      # 9 minutes
use constant REKEYFUZZ_DEFAULT   => 100;
use constant INVALID_LOCAL_IP    => 254;
use constant VPN_MAX_PROPOSALS   => 10;

use Vyatta::TypeChecker;
use Vyatta::VPN::Util;
use Getopt::Long;
use Vyatta::Misc;
use NetAddr::IP;

my $config_file;
my $secrets_file;
my $init_script;
GetOptions(
  "config_file=s"   => \$config_file,
  "secrets_file=s"  => \$secrets_file,
  "init_script=s"   => \$init_script
);
my $CA_CERT_PATH = '/etc/ipsec.d/cacerts';
my $CRL_PATH = '/etc/ipsec.d/crls';
my $SERVER_CERT_PATH = '/etc/ipsec.d/certs';
my $SERVER_KEY_PATH = '/etc/ipsec.d/private';
my $LOGFILE = '/var/log/vyatta/ipsec.log';

my $vpn_cfg_err   = "VPN configuration error:";
my $clustering_ip = 0;
my $dhcp_if = 0;
my $genout;
my $genout_secrets;

# Set $using_klips to 1 if kernel IPsec support is provided by KLIPS.
# Set it to 0 us using NETKEY.
my $using_klips = 0;

$genout         .= "# generated by $0\n\n";
$genout_secrets .= "# generated by $0\n\n";

#
# Prepare Vyatta::Config object
#
use Vyatta::Config;
my $vc    = new Vyatta::Config();
my $vcVPN = new Vyatta::Config();
$vcVPN->setLevel('vpn');

# check to see if the config has changed.
# if it has not then exit
my $ipsecstatus = $vcVPN->isChanged('ipsec');
my $rsastatus = $vcVPN->isChanged('rsa-keys');
if (!$ipsecstatus && !$rsastatus) {
  exit 0;
}
if ( $vcVPN->exists('ipsec') ) {

  #
  # Check that ESP groups have been specified
  #
  my @esp_groups = $vcVPN->listNodes('ipsec esp-group');
  if ( @esp_groups == 0 ) {

    #print STDERR "$vpn_cfg_err No ESP groups configured." .
    #             " At least one ESP group required.\n";
    # XXX for now this will be checked below for site-to-site peer

  } else {
    foreach my $esp_group (@esp_groups) {
      my @esp_group_proposals =
        $vcVPN->listNodes("ipsec esp-group $esp_group proposal");
      if ( @esp_group_proposals == 0 ) {
        vpn_die(["vpn","ipsec","esp-group",$esp_group,"proposal"],
                "$vpn_cfg_err No proposals configured for ESP group \"$esp_group\""
                . ".  At least one proposal required.\n");
      } elsif ( @esp_group_proposals > VPN_MAX_PROPOSALS ) {
        vpn_die(["vpn","ipsec","esp-group",$esp_group],
        "$vpn_cfg_err A total of "
          . @esp_group_proposals
          . " proposals have been configured for ESP group \"$esp_group\"."
          . " The maximum proposals allowed for an ESP group is "
          . VPN_MAX_PROPOSALS . "\n");
      } else {
        foreach my $esp_group_proposal (@esp_group_proposals) {
          my $esp_group_proposal_encryption = $vcVPN->returnValue(
            "ipsec esp-group $esp_group proposal $esp_group_proposal encryption"
          );
          if ( !defined($esp_group_proposal_encryption)
            || $esp_group_proposal_encryption eq "" )
          {
            vpn_die(["vpn","ipsec","esp-group",$esp_group,"proposal",$esp_group_proposal,"encryption"],
					  "$vpn_cfg_err No encryption specified for ESP group "
					  . "\"$esp_group\" proposal $esp_group_proposal.\n");
	    
          }
          my $esp_group_proposal_hash = $vcVPN->returnValue(
            "ipsec esp-group $esp_group proposal $esp_group_proposal hash");
          if ( !defined($esp_group_proposal_hash)
            || $esp_group_proposal_hash eq "" )
          {
	          vpn_die(["vpn","ipsec","esp-group",$esp_group,"proposal",$esp_group_proposal,"hash"],
					    "$vpn_cfg_err No hash specified for ESP group \"$esp_group\""
					    . " proposal $esp_group_proposal.\n");
	        }
        }
      }
    }
  }

  #
  # Check that IKE groups have been specified
  #
  my @ike_groups = $vcVPN->listNodes('ipsec ike-group');
  if ( @ike_groups == 0 ) {

    #print STDERR "$vpn_cfg_err No IKE groups configured." .
    #             "  At least one IKE group required.\n";
    # XXX for now this will be checked below for site-to-site peer

  } else {
    foreach my $ike_group (@ike_groups) {
      my @ike_group_proposals =
        $vcVPN->listNodes("ipsec ike-group $ike_group proposal");
      if ( @ike_group_proposals == 0 ) {
	      vpn_die(["vpn","ipsec","ike-group",$ike_group, "proposal"],
				    "$vpn_cfg_err No proposals configured for IKE group \"$ike_group\""
				    . ".  At least one proposal required.\n");
      } elsif ( @ike_group_proposals > VPN_MAX_PROPOSALS ) {
        vpn_die(["vpn","ipsec","ike-group",$ike_group],
        "$vpn_cfg_err A total of "
          . @ike_group_proposals
          . " proposals have been configured for IKE group \"$ike_group\"."
          . " The maximum proposals allowed for an IKE group is "
          . VPN_MAX_PROPOSALS . "\n");
      } else {
        foreach my $ike_group_proposal (@ike_group_proposals) {
          my $ike_group_proposal_encryption = $vcVPN->returnValue(
            "ipsec ike-group $ike_group proposal $ike_group_proposal encryption"
          );
          if ( !defined($ike_group_proposal_encryption)
            || $ike_group_proposal_encryption eq "" )
          {
	          vpn_die(["vpn","ike-group",$ike_group,"proposal",$ike_group_proposal,"encryption"],
					    "$vpn_cfg_err No encryption specified for IKE group "
					    . "\"$ike_group\" proposal $ike_group_proposal.\n");
          }
          my $ike_group_proposal_hash = $vcVPN->returnValue(
            "ipsec ike-group $ike_group proposal $ike_group_proposal hash");
          if ( !defined($ike_group_proposal_hash)
            || $ike_group_proposal_hash eq "" )
          {
            vpn_die(["vpn","ike-group",$ike_group,"proposal",$ike_group_proposal,"hash"],
					  "$vpn_cfg_err No hash specified for IKE group \"$ike_group\""
					  . " proposal $ike_group_proposal.\n");
          }
        }
      }
    }
  }

  #
  # Check the local key file
  # Note: $local_key_file will be used later when reading the keys
  #
  my $running_local_key_file = rsa_get_local_key_file();
  my $local_key_file         = $vcVPN->returnValue('rsa-keys local-key file');
  if ( !defined($local_key_file) ) {
    $local_key_file = LOCAL_KEY_FILE_DEFAULT;
  }
  if ( $local_key_file ne $running_local_key_file ) {

    # Sanity check the usr specified local_key_file
    #
    # 1). Must start with "/"
    # 2). Only allow alpha-numeric, ".", "-", "_", or "/".
    # 3). Don't allow "//"
    # 4). Verify that it's not a directory
    #
    if ( $local_key_file !~ /^\// ) {
      vpn_die(["vpn", "rsa-keys", "local-key", "file"],
        "$vpn_cfg_err Invalid local RSA key file path \"$local_key_file\"."
        . "  Does not start with a '/'.\n");
    }
    if ( $local_key_file =~ /[^a-zA-Z0-9\.\-\_\/]/g ) {
      vpn_die(["vpn", "rsa-keys", "local-key", "file"],
        "$vpn_cfg_err Invalid local RSA key file path \"$local_key_file\"."
        . " Contains a character that is not alpha-numeric and not '.', '-', '_', '/'.\n");
    }
    if ( $local_key_file =~ /\/\//g ) {
      vpn_die(["vpn", "rsa-keys", "local-key", "file"],
        "$vpn_cfg_err Invalid local RSA key file path \"$local_key_file\"."
        . " Contains string \"//\".\n");
    }
    if ( -d $local_key_file ) {
      vpn_die(["vpn", "rsa-keys", "local-key", "file"],
        "$vpn_cfg_err Invalid local RSA key file path \"$local_key_file\"."
        . " Path is a directory rather than a file.\n");
    }

    if ( -r $running_local_key_file && !( -e $local_key_file ) ) {
      vpn_debug "cp $running_local_key_file $local_key_file";
      my ($dirpath) = ( $local_key_file =~ m#^(.*/)?.*#s );
      my $rc = system("mkdir -p $dirpath");
      if ( $rc != 0 ) {
        vpn_die(["vpn", "rsa-keys", "local-key", "file"],
          "$vpn_cfg_err Could not copy previous local RSA key file "
          . "\"$running_local_key_file\" to new local RSA key file "
          . "\"$local_key_file\".  Could not mkdir [$dirpath] $!\n");
      } else {
        $rc = system("cp $running_local_key_file $local_key_file");
        if ( $rc != 0 ) {
          vpn_die(["vpn", "rsa-keys", "local-key", "file"],
            "$vpn_cfg_err Could not copy previous local RSA key file "
            . "\"$running_local_key_file\" to new local RSA key file "
            . "\"$local_key_file\".  $!\n");
        }
      }
    }
  }

  #
  # Version 2
  #
  $genout .= "version 2.0\n";
  $genout .= "\n";
  $genout .= "config setup\n";
  $genout .= "\tcharonstart=no\n";    # no need for charon unless we have ikev2

  #
  # Interfaces
  #
  my @interfaces = $vcVPN->returnValues('ipsec ipsec-interfaces interface');
  if ( @interfaces == 0 ) {
    #*THIS CHECK'S ALSO USED BY OP-MODE CMNDS TO CHECK IF IPSEC IS CONFIGURED*#
    vpn_die(["vpn", "ipsec","ipsec-interfaces"], 
      "$vpn_cfg_err No IPSEC interfaces specified.\n");
  } else {

    # We need to generate an "interfaces=..." entry in the setup section
    # only if the underlying IPsec kernel code we are using is KLIPS.
    # If we are using NETKEY, the "interfaces=..." entry is essentially
    # not used, though we do need to include the line and the keyword
    # "%none" to keep the IPsec setup code from defaulting the entry.
    if ($using_klips) {
      $genout .= "\tinterfaces=\"";
      my $counter = 0;
      foreach my $interface (@interfaces) {
        if ( !( -d "/sys/class/net/$interface" ) ) {
          next;
        }
        if ( $counter > 0 ) {
          $genout .= ' ';
        }
        $genout .= "ipsec$counter=$interface";
        ++$counter;
      }
      if ( hasLocalWildcard( $vcVPN, 0 ) ) {
        if ( $counter > 0 ) {
          $genout .= ' ';
        }
        $genout .= '%defaultroute';
      }
      $genout .= "\"\n";
    } else {
      my $counter = 0;
      $genout .= "\t";
      if ( hasLocalWildcard( $vcVPN, 0 ) ) {
        $genout .= 'interfaces="';
        foreach my $interface (@interfaces) {
          next if !-d "/sys/class/net/$interface";
          next if scalar( getIP($interface) ) < 1;
          $genout .= "ipsec$counter=$interface ";
          ++$counter;
        }
        $genout .= '%defaultroute"';
      } else {
        $genout .= 'interfaces="%none"';
      }
      $genout .= "\n";
    }
  }

  #
  # NAT traversal
  #
  my $nat_traversal = $vcVPN->returnValue('ipsec nat-traversal');
  if ( defined($nat_traversal) ) {
    if ( $nat_traversal eq 'enable' ) {
      $genout .= "\tnat_traversal=yes\n";
    } elsif ( $nat_traversal eq 'disable' ) {
      $genout .= "\tnat_traversal=no\n";
    } elsif ( $nat_traversal ne '' ) {
      vpn_die(["vpn", "ipsec", "nat-traversal"],
        "$vpn_cfg_err Invalid value \"$nat_traversal\" specified for "
        . "'nat-traversal'.  Only \"enable\" or \"disable\" accepted.\n");
    }
  }

  #
  # NAT networks
  #
  my @nat_networks = $vcVPN->listNodes('ipsec nat-networks allowed-network');
  if ( @nat_networks > 0 ) {
    my $first_nat_net = 1;
    foreach my $nat_network (@nat_networks) {
      if ($first_nat_net) {
        $genout .= "\tvirtual_private=\"\%v4:$nat_network";
        $first_nat_net = 0;
      } else {
        $genout .= ",\%v4:$nat_network";
      }

      my @nat_network_excludes = $vcVPN->returnValues(
        "ipsec nat-networks allowed-network $nat_network exclude");
      foreach my $nat_network_exclude (@nat_network_excludes) {
        $genout .= ",\%v4:\!$nat_network_exclude";
      }
    }
    $genout .= "\"\n";
  }

  #
  # log-mode
  #
  my @logmodes = $vcVPN->returnValues('ipsec logging log-modes');
  if ( @logmodes > 0 ) {
    my $debugmode = '';
    foreach my $mode (@logmodes) {
      if ( $mode eq "all" ) {
        $debugmode = "all";
        last;
      }
      if ( $debugmode eq '' ) {
        $debugmode = "$mode";
      } else {
        $debugmode .= " $mode";
      }
    }
    $genout .= "\tplutodebug=\"$debugmode\"\n";
  }

  # Set plutoopts:
  # Disable uniqreqids?
  #
  if ( $vcVPN->exists('ipsec disable-uniqreqids') ) {
    $genout .= "\tdisableuniqreqids=yes\n";
  }

  #
  # Disable implicit connections
  #
  foreach my $conn (
    qw/clear clear-or-private private-or-clear private block packetdefault/)
  {
    $genout .= "\n";
    $genout .= "conn $conn\n";
    $genout .= "\tauto=ignore\n";
  }

  #
  # Connection configurations
  #
  my @peers = $vcVPN->listNodes('ipsec site-to-site peer');
  if ( @peers == 0 && !( $vcVPN->exists('l2tp') ) ) {
    print "VPN Warning: IPSec configured but no site-to-site peers or l2tp"
      . " remote-users configured\n";
  }
  my $prev_peer = "";
  foreach my $peer (@peers) {
    my $peer_ike_group =
      $vcVPN->returnValue("ipsec site-to-site peer $peer ike-group");
    if ( !defined($peer_ike_group) || $peer_ike_group eq '' ) {
      vpn_die(["vpn","ipsec","site-to-site","peer",$peer,"ike-group"],
				  "$vpn_cfg_err No IKE group specified for peer \"$peer\".\n");
    } elsif ( !$vcVPN->exists("ipsec ike-group $peer_ike_group") ) {
      vpn_die(["vpn","ipsec","site-to-site","peer",$peer,"ike-group"],
				  "$vpn_cfg_err The IKE group \"$peer_ike_group\" specified for peer "
				  . "\"$peer\" has not been configured.\n");
    }

    my $lip = $vcVPN->returnValue("ipsec site-to-site peer $peer local-ip");
    my $dhcp_iface = $vcVPN->returnValue("ipsec site-to-site peer $peer dhcp-interface");
    if (defined($lip) && defined($dhcp_iface)){
      vpn_die(["vpn","ipsec","site-to-site","peer",$peer],
        "$vpn_cfg_err Only one of local-ip or dhcp-interface may be defined");
    }
    if (defined($dhcp_iface)){
      $dhcp_if = $dhcp_if + 1;
      $lip = get_dhcp_addr($dhcp_iface, $peer);
    }
    my $authid =
      $vcVPN->returnValue("ipsec site-to-site peer $peer authentication id");
    my $authremoteid = $vcVPN->returnValue(
      "ipsec site-to-site peer $peer authentication remote-id");
    if ( (!defined($lip) || $lip eq "") && (!defined($dhcp_iface) || $dhcp_iface eq "") ) {
      vpn_die(["vpn","ipsec","site-to-site","peer",$peer,"local-ip"],
        "$vpn_cfg_err No local-ip specified for peer \"$peer\"\n");
    } elsif ( $lip ne '0.0.0.0' ) {

      # not '0.0.0.0' special case.
      # check interface addresses.
      if ( !Vyatta::Misc::isIPinInterfaces( $vc, $lip, @interfaces ) ) {
        vpn_log(
"The local-ip address $lip of peer \"$peer\" has not been configured in any of the ipsec-interfaces.\n"
        );
        if ( Vyatta::Misc::isClusterIP( $vc, $lip ) ) {

          # Verified that dealing with a cluster IP.
          $clustering_ip = 1;
        } elsif (!defined($dhcp_iface)) {
          print
            "Warning: Local IPv4 address $lip specified for peer \"$peer\"\n";
          print
            "is not configured on any of the ipsec-interfaces and is not the\n";
          print "clustering address.  IPsec must be re-started after address\n";
          print "has been configured.\n";
          print "\n";
        }
      }
    }
    
    #
    # Default ESP group
    #
    my $def_esp_group = $vcVPN->returnValue("ipsec site-to-site peer $peer default-esp-group");
    $def_esp_group = '' if !defined($def_esp_group);
    if ( !$vcVPN->exists("ipsec esp-group $def_esp_group") ) {
        vpn_die(["vpn","ipsec","site-to-site","peer",$peer,"default-esp-group"],
				    "$vpn_cfg_err The ESP group \"$def_esp_group\" specified "
				    . "for peer \"$peer\" has not been configured.\n");
    }

    #
    # Name connection by peer and tunnel
    #
    my @tunnels = $vcVPN->listNodes("ipsec site-to-site peer $peer tunnel");
    if ( @tunnels == 0 ) {
      vpn_die(["vpn", "ipsec", "site-to-site","peer",$peer,"tunnel"],
        "$vpn_cfg_err No tunnels configured for peer \"$peer\".  At least"
        . " one tunnel required per peer.\n");
    }
    foreach my $tunnel (@tunnels) {

      my $needs_passthrough = 'false';

      #
      # Add support for tunnel disable.
      #
      if (
        $vcVPN->exists("ipsec site-to-site peer $peer tunnel $tunnel disable") )
      {
        next;
      }

      my $peer_tunnel_esp_group = $vcVPN->returnValue(
        "ipsec site-to-site peer $peer tunnel $tunnel esp-group");
      $peer_tunnel_esp_group = '' if (!defined($peer_tunnel_esp_group));
      if ( (!defined($peer_tunnel_esp_group) || $peer_tunnel_esp_group eq '') && 
           (!defined($def_esp_group) || $def_esp_group eq '')) {
        vpn_die(["vpn","ipsec","site-to-site","peer",$peer,"tunnel",$tunnel,"esp-group"],
				    "$vpn_cfg_err No ESP group specified for peer \"$peer\" "
				    . "tunnel $tunnel.\n");
      } elsif ( !$vcVPN->exists("ipsec esp-group $peer_tunnel_esp_group") ) {
        vpn_die(["vpn","ipsec","site-to-site","peer",$peer,"tunnel",$tunnel,"esp-group"],
				    "$vpn_cfg_err The ESP group \"$peer_tunnel_esp_group\" specified "
				    . "for peer \"$peer\" tunnel $tunnel has not been configured.\n");
      }

      my $conn_head = "\nconn peer-$peer-tunnel-$tunnel\n";
      $conn_head =~ s/ peer-@/ peer-/;
      $genout .= $conn_head;
      
      # Support for dhcp-interfaces
      # The comment dhcp-interface will be used by the dhclient hook to do connection updates.
      if (defined($dhcp_iface)){
        $genout .= "\t\#dhcp-interface=$dhcp_iface\n";
        $lip = get_dhcp_addr($dhcp_iface);
      }

      # -> leftsourceip is the internal source IP to use in a tunnel
      # -> we use leftsourceip to add a route to the rightsubnet
      #    only when rightsubnet is defined and is not 0.0.0.0/0. we do not
      #    want to add a vpn route for everything i.e. rightsubnet = 0.0.0.0/0
      # -> if leftsubnet is defined and is not 0.0.0.0/0; we try and find
      #    an interface on the system that has an IP address lying within
      #    the leftsubnet and use that as leftsourceip. if leftsubnet is not
      #    defined or is 0.0.0.0/0 then we use local-ip as leftsourceip.
      my $leftsourceip = undef;

      #
      # Assign left and right to local and remote interfaces
      #
      if ( defined($lip) ) {
        if ( $lip eq '0.0.0.0' ) {
          $genout .= "\tleft=%defaultroute\n";
          # no need for leftsourceip as a defaultroute is must for this to work
        } else {
          $genout .= "\tleft=$lip\n";
          $leftsourceip = "\tleftsourceip=$lip\n";
        }
        $genout .= "\tleftid=$authid\n" if defined $authid;
      }

      my $any_peer = 0;
      my $right;
      my $rightid = undef;
      if ( $peer =~ /^\@/ ) {

        # peer is an "ID"
        $rightid  = $peer;
        $any_peer = 1;
      } elsif ($authremoteid) {
        $rightid = $authremoteid;
      }
      if ( ( $peer eq 'any' )
        or ( $peer eq '0.0.0.0' )
        or $any_peer == 1 )
      {
        $right    = '%any';
        $any_peer = 1;
      } else {
        $right = $peer;
      }
      $genout .= "\tright=$right\n";
      $genout .= "\trightid=\"$rightid\"\n" if ( defined($rightid) );
      if ($any_peer) {
        $genout .= "\trekey=no\n";
      }

      #
      # Write tunnel configuration
      #
      my $leftsubnet = $vcVPN->returnValue(
        "ipsec site-to-site peer $peer tunnel $tunnel local subnet");
      if ( defined($leftsubnet) && $leftsubnet eq 'any' ) {
        $leftsubnet = '0.0.0.0/0';
      }

      if ( defined($leftsubnet) ) {
        $genout .= "\tleftsubnet=$leftsubnet\n";
        if ( !( $leftsubnet eq '0.0.0.0/0' ) ) {
          my $localsubnet_object = new NetAddr::IP($leftsubnet);

        # leftsourceip should now be an IP on system lying within the leftsubnet
          my @system_ips = Vyatta::Misc::getIP( undef, '4' );
          foreach my $system_ip (@system_ips) {
            my $systemip_object = new NetAddr::IP($system_ip);
            if (
              CheckIfAddressInsideNetwork(
                $systemip_object, $localsubnet_object
              )
              )
            {
              my $sourceip = $systemip_object->addr();
              $leftsourceip = "\tleftsourceip=$sourceip\n";
            }
          }
        }
      }

      my $remotesubnet = $vcVPN->returnValue(
        "ipsec site-to-site peer $peer tunnel $tunnel remote subnet");

      my $rightsubnet;
      my $allow_nat_networks = $vcVPN->returnValue(
        "ipsec site-to-site peer $peer tunnel $tunnel allow-nat-networks");
      my $allow_public_networks = $vcVPN->returnValue(
        "ipsec site-to-site peer $peer tunnel $tunnel allow-public-networks");

      if ( defined($allow_nat_networks) && $allow_nat_networks eq 'enable' ) {
        if ( defined($remotesubnet) && $remotesubnet ne "" ) {
          vpn_die(["vpn","ipsec","site-to-site","peer",$peer,"tunnel", $tunnel],
            "$vpn_cfg_err The 'remote-subnet' has been specified while "
            . "'allow-nat-networks' has been enabled for peer \"$peer\" tunnel "
            . "$tunnel.  Both not allowed at once.\n");
        }

        my @allowed_network =
          $vcVPN->listNodes('ipsec nat-networks allowed-network');
        if ( @allowed_network == 0 ) {
          vpn_die(["vpn","ipsec","site-to-site","peer",$peer,"tunnel", $tunnel],
            "$vpn_cfg_err While 'allow-nat-networks' has been enabled for peer"
            . " \"$peer\" tunnel $tunnel, no global allowed NAT networks have"
            . " been configured.\n");
        }

        $rightsubnet = "vhost:%priv";
        if ( defined($allow_public_networks)
          && $allow_public_networks eq "enable" )
        {
          if ( defined($remotesubnet) && $remotesubnet ne "" ) {
            vpn_die(["vpn","ipsec","site-to-site","peer",$peer,"tunnel", $tunnel],
              "$vpn_cfg_err The 'remote-subnet' has been specified while "
              . "'allow-public-networks' has been enabled for peer \"$peer\" "
              . "tunnel $tunnel.  Both not allowed at once.\n");
          }
          $rightsubnet .= ",%no";
        }
      } else {
        $rightsubnet = $remotesubnet;
        if ( defined($rightsubnet) && $rightsubnet eq 'any' ) {
          $rightsubnet = '0.0.0.0/0';
        }
      }
      if ( defined($rightsubnet) ) {
        $genout .= "\trightsubnet=$rightsubnet\n";

        # not adding vpn route if remote subnet is 0.0.0.0/0
        # user should add a route [default/static] manually
        $leftsourceip = undef if $rightsubnet eq '0.0.0.0/0';
        if ($rightsubnet =~ /vhost:%priv/) {
          # can't add route when rightsubnet is not specific
          $leftsourceip = undef;
        }
      } else {
        $leftsourceip =
          undef;    # no need for vpn route if rightsubnet not defined
      }

      $genout .= $leftsourceip if defined $leftsourceip;

      #
      # Protocol/port
      #
      my $protocol = $vcVPN->returnValue(
          "ipsec site-to-site peer $peer tunnel $tunnel protocol");
      my $lprotoport = '';
      if (defined($protocol)){
          $lprotoport .= $protocol; 
      }
      my $lport = $vcVPN->returnValue(
          "ipsec site-to-site peer $peer tunnel $tunnel local port");
      if (defined($lport)){
          if (!defined($protocol)){
            $lprotoport .= "0/$lport";
          } elsif (is_tcp_udp($protocol)){
            $lprotoport .= "/$lport";
          } else {
            vpn_die(["vpn","ipsec","site-to-site","peer",$peer, "tunnel", $tunnel, "local", "port"],
                "$vpn_cfg_err local port can only be defined when protocol is tcp, udp, or undefined.\n");
          }
      }
      if (not ($lprotoport eq '')){
        $genout .= "\tleftprotoport=$lprotoport\n";
      }

      my $rprotoport = '';
      if (defined($protocol)){
          $rprotoport .= $protocol; 
      }
      my $rport = $vcVPN->returnValue(
          "ipsec site-to-site peer $peer tunnel $tunnel remote port");
      if (defined($rport)){
          if (!defined($protocol)){
            $rprotoport .= "0/$rport";
          } elsif (is_tcp_udp($protocol)){
            $rprotoport .= "/$rport";
          } else {
            vpn_die(["vpn","ipsec","site-to-site","peer",$peer, "tunnel", $tunnel, "remote", "port"],
                "$vpn_cfg_err remote port can only be defined when protocol is tcp, udp, or undefined.\n");
          }
      }
      if (not ($rprotoport eq '')){
        $genout .= "\trightprotoport=$rprotoport\n";
      }


      #
      # check if passthrough connection is needed
      # needed when remote-subnet encompasses local-subnet
      #
      if (defined $leftsubnet && defined $rightsubnet) {
        # validate that these values are ipv4net
        my $valid_leftsubnet = 'false';
        my $valid_rightsubnet = 'false';

        $valid_leftsubnet = 'true' if validateType( 'ipv4net', $leftsubnet, 'quiet' );
        $valid_rightsubnet = 'true' if validateType( 'ipv4net', $rightsubnet, 'quiet' );

        if ($valid_leftsubnet eq 'true' && $valid_rightsubnet eq 'true') {

          my $localsubnet_object = new NetAddr::IP($leftsubnet);
          my $remotesubnet_object = new NetAddr::IP($rightsubnet);
          if ($remotesubnet_object == $localsubnet_object) {
            vpn_die(["vpn","ipsec","site-to-site","peer",$peer],
                "$vpn_cfg_err local subnet and remote subnet cannot be the same.\n");
          }
          if ($remotesubnet_object->contains($localsubnet_object)) {
            $needs_passthrough = 'true';
          } 
        }
      }

      #
      # Write IKE configuration from group
      #
      my $ikelifetime = IKELIFETIME_DEFAULT;
      $genout .= "\tike=";
      my $ike_group =
        $vcVPN->returnValue("ipsec site-to-site peer $peer ike-group");
      if ( defined($ike_group) && $ike_group ne '' ) {
        my @ike_proposals =
          $vcVPN->listNodes("ipsec ike-group $ike_group proposal");

        my $first_ike_proposal = 1;
        foreach my $ike_proposal (@ike_proposals) {

          #
          # Get encryption, hash & Diffie-Hellman  key size
          #
          my $encryption = $vcVPN->returnValue(
            "ipsec ike-group $ike_group proposal $ike_proposal encryption");
          my $hash = $vcVPN->returnValue(
            "ipsec ike-group $ike_group proposal $ike_proposal hash");
          my $dh_group = $vcVPN->returnValue(
            "ipsec ike-group $ike_group proposal $ike_proposal dh-group");

          #
          # Write separator if not first proposal
          #
          if ($first_ike_proposal) {
            $first_ike_proposal = 0;
          } else {
            $genout .= ",";
          }

          #
          # Write values
          #
          if ( defined($encryption) && defined($hash) ) {
            $genout .= "$encryption-$hash";
            if ( defined($dh_group) ) {
              if ( $dh_group eq '2' ) {
                $genout .= '-modp1024';
              } elsif ( $dh_group eq '5' ) {
                $genout .= '-modp1536';
              } elsif ( $dh_group ne '' ) {
                vpn_die(["vpn","ipsec","site-to-site","peer",$peer,"tunnel", $tunnel],
                  "$vpn_cfg_err Invalid 'dh-group' $dh_group specified for "
                  . "peer \"$peer\" tunnel $tunnel.  Only 2 or 5 accepted.\n");
              }
            }
          }
        }
        $genout .= "!\n";

        my $t_ikelifetime =
          $vcVPN->returnValue("ipsec ike-group $ike_group lifetime");
        if ( defined($t_ikelifetime) && $t_ikelifetime ne '' ) {
          $ikelifetime = $t_ikelifetime;
        }
        $genout .= "\tikelifetime=$ikelifetime" . "s\n";

        #
        # Check for Dead Peer Detection DPD
        #
        my $dpd_interval = $vcVPN->returnValue(
          "ipsec ike-group $ike_group dead-peer-detection interval");
        my $dpd_timeout = $vcVPN->returnValue(
          "ipsec ike-group $ike_group dead-peer-detection timeout");
        my $dpd_action = $vcVPN->returnValue(
          "ipsec ike-group $ike_group dead-peer-detection action");
        if ( defined($dpd_interval)
          && defined($dpd_timeout)
          && defined($dpd_action) )
        {
          $genout .= "\tdpddelay=$dpd_interval" . "s\n";
          $genout .= "\tdpdtimeout=$dpd_timeout" . "s\n";
          $genout .= "\tdpdaction=$dpd_action\n";
        }
      }


      #
      # Write ESP configuration from group
      #
      my $esplifetime = ESPLIFETIME_DEFAULT;
      $genout .= "\tesp=";
      my $esp_group = $vcVPN->returnValue(
        "ipsec site-to-site peer $peer tunnel $tunnel esp-group");
      if (!defined($esp_group) || $esp_group eq ''){
        $esp_group = $vcVPN->returnValue(
          "ipsec site-to-site peer $peer default-esp-group");
      }
      if ( defined($esp_group) && $esp_group ne '' ) {
        my @esp_proposals =
          $vcVPN->listNodes("ipsec esp-group $esp_group proposal");
        my $first_esp_proposal = 1;
        foreach my $esp_proposal (@esp_proposals) {

          #
          # Get encryption, hash
          #
          my $encryption = $vcVPN->returnValue(
            "ipsec esp-group $esp_group proposal $esp_proposal encryption");
          my $hash = $vcVPN->returnValue(
            "ipsec esp-group $esp_group proposal $esp_proposal hash");

          #
          # Write separator if not first proposal
          #
          if ($first_esp_proposal) {
            $first_esp_proposal = 0;
          } else {
            $genout .= ",";
          }

          #
          # Write values
          #
          if ( defined($encryption) && defined($hash) ) {
            $genout .= "$encryption-$hash";
          }
        }
        $genout .= "!\n";

        my $t_esplifetime =
          $vcVPN->returnValue("ipsec esp-group $esp_group lifetime");
        if ( defined($t_esplifetime) && $t_esplifetime ne '' ) {
          $esplifetime = $t_esplifetime;
        }
        $genout .= "\tkeylife=$esplifetime" . "s\n";

        my $lower_lifetime = $ikelifetime;
        if ( $esplifetime < $ikelifetime ) {
          $lower_lifetime = $esplifetime;
        }

        #
        # The lifetime values need to be greater than:
        #   rekeymargin*(100+rekeyfuzz)/100
        #
        my $rekeymargin = REKEYMARGIN_DEFAULT;
        if ( $lower_lifetime <= ( 2 * $rekeymargin ) ) {
          $rekeymargin = int( $lower_lifetime / 2 ) - 1;
        }
        $genout .= "\trekeymargin=$rekeymargin" . "s\n";

        #
        # Mode (tunnel or transport)
        #
        my $espmode = $vcVPN->returnValue("ipsec esp-group $esp_group mode");
        if ( !defined($espmode) || $espmode eq '' ) {
          $espmode = "tunnel";
        }
        if ( $espmode eq "transport" ) {
          if ( defined $leftsubnet or defined $rightsubnet ) {
            vpn_die(["vpn","ipsec","site-to-site","peer",$peer,"tunnel", $tunnel],
              "$vpn_cfg_err Can not use local-subnet or remote-subnet when "
              . "using transport mode\n");
          }
        }
        $genout .= "\ttype=$espmode\n";

        #
        # Perfect Forward Secrecy
        #
        my $pfs = $vcVPN->returnValue("ipsec esp-group $esp_group pfs");
        if ( defined($pfs) ) {
          if ( $pfs eq 'enable' ) {
            $genout .= "\tpfs=yes\n";
          } elsif ( $pfs eq 'dh-group2' ) {
            $genout .= "\tpfs=yes\n";
            $genout .= "\tpfsgroup=modp1024\n";
          } elsif ( $pfs eq 'dh-group5' ) {
            $genout .= "\tpfs=yes\n";
            $genout .= "\tpfsgroup=modp1536\n";
          } else {
            $genout .= "\tpfs=no\n";
          }
        }

        #
        # Compression
        #
        my $compression =
          $vcVPN->returnValue("ipsec esp-group $esp_group compression");
        if ( defined($compression) ) {
          if ( $compression eq 'enable' ) {
            $genout .= "\tcompress=yes\n";
          } else {
            $genout .= "\tcompress=no\n";
          }
        }
      }

      #
      # Authentication mode
      #
      #
      # Write shared secrets to ipsec.secrets
      #
      my $auth_mode = $vcVPN->returnValue(
        "ipsec site-to-site peer $peer authentication mode");
      if ( !defined($auth_mode) || $auth_mode eq '' ) {
        vpn_die(["vpn","ipsec","site-to-site","peer",$peer,"authentication"],
             "$vpn_cfg_err No authentication mode for peer \"$peer\" specified.\n");
      } elsif ( defined($auth_mode) && ( $auth_mode eq 'pre-shared-secret' ) ) {
        my $psk = $vcVPN->returnValue(
          "ipsec site-to-site peer $peer authentication pre-shared-secret");
        my $orig_psk = $vcVPN->returnOrigValue(
          "ipsec site-to-site peer $peer authentication pre-shared-secret");
        $orig_psk = "" if (!defined($orig_psk));
        if ($psk ne $orig_psk && $orig_psk ne ""){
          print "WARNING: The pre-shared-secret will not be updated until the next re-keying interval\n";
          print "To force the key change use: 'reset vpn ipsec-peer'\n";
        }
        if ( !defined($psk) || $psk eq '' ) {
          vpn_die(["vpn","ipsec","site-to-site","peer",$peer,"authentication"],
            "$vpn_cfg_err No 'pre-shared-secret' specified for peer \"$peer\""
            . " while 'pre-shared-secret' authentication mode is specified.\n");
        }

        my $right;
        if ( ( $peer eq 'any' )
          or ( $peer eq '0.0.0.0' )
          or ( $peer =~ /^\@/ ) )
        {
          $right = '%any';
        } else {
          $right = $peer;
        }
        my $index1 = ( defined($authid) )       ? "$authid"       : $lip;
        my $index2 = ( defined($authremoteid) ) ? "$authremoteid" : $right;
        if ($lip eq '0.0.0.0'&&!defined($dhcp_iface)) {
          if ($index1 =~ m/^@/) {
            # In main mode PSK, the responder needs to look up the secret 
            # before the Peer's ID payload has been decoded, so the ID used 
            # will be the IP address. Note that this'll work with aggressive 
            # mode PSK but starting VC6, we use strongswan which doesn't 
            # support aggressive mode. More info on reported bug :
            # http://bugzilla.vyatta.com/show_bug.cgi?id=5500            
	          vpn_die(["vpn","ipsec","site-to-site","peer","0.0.0.0","authentication"],
					  "$vpn_cfg_err cannot use authentication id with pre-shared-secret"
					  . " when local-ip is 0.0.0.0\n");
		}
	    # when local-ip is dynamic then only the following generic form works
	    $genout_secrets .= ": PSK \"$psk\"\n";
        } else {
          if (not ($prev_peer eq $peer)){
            if (defined($dhcp_iface) && $lip eq ''){
              $genout_secrets .= "# $right ";
            } else {
              $genout_secrets .= "$lip $right ";
            }
            if ( defined ($authid) ){
              $genout_secrets .= "$authid ";
            }
            if ( defined ($authremoteid) ) {
              $genout_secrets .= "$authremoteid ";
            }
	          # tag the secrets lines with 3 entries so the op mode command can
	          # deal with them properly. (LEFT means localid, RIGHT means remoteid)
            if ((!defined($authid)) && (defined($authremoteid))) {
              $genout_secrets .= ": PSK \"$psk\" #RIGHT# ";
            } elsif ((defined($authid)) && (!defined($authremoteid))) {
              $genout_secrets .= ": PSK \"$psk\" #LEFT# ";
            } else {
              $genout_secrets .= ": PSK \"$psk\" ";
            }
            if (defined($dhcp_iface)){
              $genout_secrets .= "#dhcp-interface=$dhcp_iface#\n";
            } else {
              $genout_secrets .= "\n";
            }
          }
          $prev_peer = $peer;
        }
        $genout         .= "\tauthby=secret\n";
      } elsif ( defined($auth_mode) && $auth_mode eq 'x509') {
        $genout .= get_x509($peer);
        $genout_secrets .= get_x509_secret($peer);
      } elsif ( defined($auth_mode) && $auth_mode eq 'rsa' ) {

        unless ( -r $local_key_file ) {
          if ( -e $local_key_file ) {
          vpn_die(["vpn","ipsec","site-to-site","peer",$peer,"authentication"],
            "$vpn_cfg_err Invalid local RSA key file path "
              . "\"$local_key_file\".  Filesystem read permission absent.\n");
          } else {
          vpn_die(["vpn","ipsec","site-to-site","peer",$peer,"authentication"],
              "$vpn_cfg_err Invalid local RSA key file path \"$local_key_file\"."
              . " File absent.  Use the 'vpn rsa-key generate' command to create.\n");
          }
        }

        $genout .= "\tauthby=rsasig\n";
        my $local_key = rsa_get_local_pubkey($local_key_file);
        if ( !defined($local_key) || $local_key eq "" ) {
          vpn_die(["vpn","ipsec","site-to-site","peer",$peer,"authentication"],
            "$vpn_cfg_err Unable to determine local public key from local key"
            . " file \"$local_key_file\" for peer \"$peer\".\n");
        } else {
          $genout .= "\tleftrsasigkey=\"$local_key\"\n";
        }

        my $rsa_key_name = $vcVPN->returnValue(
          "ipsec site-to-site peer $peer authentication rsa-key-name");
        if ( !defined($rsa_key_name) || $rsa_key_name eq "" ) {
          vpn_die(["vpn","ipsec","site-to-site","peer",$peer,"authentication","rsa-key-name"],
            "$vpn_cfg_err No 'rsa-key-name' specified for peer \"$peer\""
            . " while 'rsa' authentication mode is specified.\n");
        } else {
          my $remote_key =
            $vcVPN->returnValue("rsa-keys rsa-key-name $rsa_key_name rsa-key");
          if ( !defined($remote_key) || $remote_key eq "" ) {
            vpn_die(["vpn","ipsec","site-to-site","peer",$peer,"authentication"],
              "$vpn_cfg_err No remote key configured for rsa key name "
              . "\"$rsa_key_name\" that is specified for peer \"$peer\".\n");
          } else {
            $genout .= "\trightrsasigkey=\"$remote_key\"\n";
          }
        }
        $genout_secrets .= "include $local_key_file\n";
      } else {
        vpn_die(["vpn","ipsec","site-to-site","peer",$peer,"authentication"],
          "$vpn_cfg_err Unknown authentication mode \"$auth_mode\" for peer "
          . "\"$peer\" specified.\n");
      }

      #
      # Start automatically
      #
      if ($any_peer) {
        $genout .= "\tauto=add\n";
        $genout .= "\tkeyingtries=%forever\n";      
      } else {
        my $conntype = $vcVPN->returnValue("ipsec site-to-site peer $peer connection-type");
        if (defined ($conntype)){
          if ($conntype eq "initiate"){
            $genout .= "\tauto=start\n";
            $genout .= "\tkeyingtries=%forever\n";      
          } elsif ($conntype eq "respond"){
            $genout .= "\tauto=add\n";
            $genout .= "\tkeyingtries=1\n";      
          }
        }
        else{
          $genout .= "\tauto=start\n";
        }
      }
      $conn_head =~ s/\n//;
      $genout .= "#$conn_head";    # to identify end of connection definition
                                   # used by clear vpn op-mode command

      if ( $needs_passthrough eq 'true' ) {

          # CREATE A PASSTHROUGH CONNECTION
          my $passthrough_conn_head = "\nconn passthrough-peer-$peer-tunnel-$tunnel\n";
          $passthrough_conn_head =~ s/ peer-@/ peer-/;
          $genout .= $passthrough_conn_head;
          if ( $lip eq '0.0.0.0' ) {
            $genout .= "\tleft=%defaultroute\n";
          } else {
            $genout .= "\tleft=$lip\n";
          }
          $genout .= "\tright=$right\n";
          $genout .= "\tleftsubnet=$leftsubnet\n";
          $genout .= "\trightsubnet=$leftsubnet\n";
          $genout .= "\ttype=passthrough\n";
          $genout .= "\tauthby=never\n";
          $genout .= "\tauto=route\n";
          $passthrough_conn_head =~ s/\n//;
          $genout .= "#$passthrough_conn_head";

      }

    }
  }
} else {

  #
  # remove any previous config lines, so that when "clear vpn ipsec-process"
  # is called it won't find the vyatta keyword and therefore will not try
  # to start the ipsec process.
  #
  $genout = '';
  $genout         .= "# No VPN configuration exists.\n";
  $genout_secrets .= "# No VPN configuration exists.\n";
}

if (
  !(
       defined($config_file)
    && ( $config_file ne '' )
    && defined($secrets_file)
    && ( $secrets_file ne '' )
  )
  )
{
  print "Regular config file output would be:\n\n$genout\n\n";
  print "Secrets config file output would be:\n\n$genout_secrets\n\n";
  exit(0);
}

if ( $vcVPN->isDeleted('.')
    || !$vcVPN->exists('.')
    || $vcVPN->isDeleted('ipsec')
    || !$vcVPN->exists('ipsec') )
{
  if ( Vyatta::Misc::isClusterIP( $vc, 'ipsec' ) ) {
    vpn_die(["vpn","ipsec"],
     "VPN commit error.  Cluster service is referencing ipsec config.\n");
  }
  if ( is_vpn_running() ) {
    vpn_exec( 'ipsec stop >&/dev/null', 'stop ipsec' );
  }
  if ( !enableICMP('1') ) {
    vpn_die(["vpn","ipsec"],
    "VPN commit error.  Unable to re-enable ICMP redirects.\n");
  }
  write_config( $genout, $config_file, $genout_secrets, $secrets_file, $dhcp_if);
} else {
  if ( !enableICMP('0') ) {
    vpn_die(["vpn","ipsec"],
    "VPN commit error.  Unable to disable ICMP redirects.\n");
  }

  write_config( $genout, $config_file, $genout_secrets, $secrets_file, $dhcp_if );

 # Assumming that if there was a local IP missmatch and clustering is enabled,
 # then the clustering scripts will take care of starting the VPN daemon.
  if ($clustering_ip) {

# If the local-ip is provided by clustering, then just write out the configuration,
# but do not start the VPN daemon

    vpn_log(
"Wrote out configuration to files '$config_file' and '$secrets_file'.  VPN/ipsec daemons not started due to clustering.\n"
      );
      print "Clustering configured - not restarting ipsec\n";
  } else {
    my $update_interval = $vcVPN->returnValue("ipsec auto-update");
    my $update_interval_orig = $vcVPN->returnOrigValue("ipsec auto-update");
    $update_interval_orig = 0 if !defined($update_interval_orig);
    if ( is_vpn_running() ) {
      if (defined($update_interval) && ($update_interval != $update_interval_orig)){
        print "Re-starting IPsec daemon to activate new auto-update interval...\n";
        vpn_exec( 'ipsec restart --auto-update '.$update_interval.' >&/dev/null', 
                  're-starting ipsec with updated auto-update interval $update_interval' );
      } elsif (!defined($update_interval) && ($update_interval_orig != 0)){
        print "Re-starting IPsec daemon to deactivate auto-update...\n";
        vpn_exec( 'ipsec restart >&/dev/null', 're-starting ipsec' );
      }
      else {
        vpn_exec( 'ipsec rereadall >&/dev/null', 're-read secrets and certs' );
        vpn_exec( 'ipsec update >&/dev/null', 'update changes to ipsec.conf' );
      }
    } else {
      if (! defined($update_interval) ) {
        vpn_exec( 'ipsec start >&/dev/null', 'start ipsec' );
      } else {
        vpn_exec( 'ipsec start --auto-update '.$update_interval.' >&/dev/null', 
                 'start ipsec with auto-update $update_interval' );
      }
    }
  }
}


#
# Return success
#
exit 0;
sub vpn_die {
  my (@path,$msg) = @_;
  Vyatta::Config::outputError(@path, $msg);
  exit 1;
}
sub write_config {
  my ( $genout, $config_file, $genout_secrets, $secrets_file, $dhcp_if ) = @_;

  open my $output_config, '>', $config_file
    or die "Can't open $config_file: $!";
  print ${output_config} $genout;
  close $output_config;

  open my $output_secrets, '>', $secrets_file
    or die "Can't open $secrets_file: $!";
  print ${output_secrets} $genout_secrets;
  close $output_secrets;
  dhcp_hook($dhcp_if);
}

sub vpn_exec {
  my ( $command, $desc ) = @_;

  open my $logf, '>>', $LOGFILE
    or die "Can't open $LOGFILE: $!";

  use POSIX;
  my $timestamp = strftime( "%Y-%m-%d %H:%M.%S", localtime );

  print ${logf} "$timestamp\nExecuting: $command\nDescription: $desc\n";

  my $cmd_out = qx($command);
  my $rval    = ( $? >> 8 );
  print ${logf} "Output:\n$cmd_out\n---\n";
  print ${logf} "Return code: $rval\n";
  if ($rval) {
    if ( $command =~ /^ipsec.*--asynchronous$/
      && ( $rval == 104 || $rval == 29 ) )
    {
      print ${logf} "OK when bringing up VPN connection\n";
    } else {

        #
        # We use to consider the commit failed if we got a error
        # from the call to ipsec, but this causes the configuration
        # to not get included in the running config.  Now that
        # we support dynamic interface/address (e.g. dhcp, pppoe)
        # we want a valid config to get committed even if the
        # interface doesn't exist yet.  That way we can use
        # "clear vpn ipsec-process" to bring up the tunnel once
        # the interface is instantiated.  For pppoe we will add
        # a script to /etc/ppp/ip-up.d to bring up the vpn
        # tunnel.
        #
      print ${logf}
        "VPN commit error.  Unable to $desc, received error code $?\n";
      #
      # code 768 is for a syntax error in the secrets file
      # this happens when a dhcp interface is configured
      # but no address is assigned yet.
      # only the line that has the syntax error is not loaded
      # So we can safely ignore this error since our code generates
      # secrets file.
      #
      if ($? ne '768'){
        print "Warning: unable to [$desc], received error code $?\n"; 
        print "$cmd_out\n";
      }
    }
  }
  print ${logf} "---\n\n";
  close $logf;
}

sub vpn_log {
  my ($log) = @_;

  open my $logfile, '>>', $LOGFILE
    or die "Can't open $LOGFILE: $!";

  use POSIX;
  my $timestamp = strftime( "%Y-%m-%d %H:%M.%S", localtime );

  print ${logfile} "$timestamp\n$log\n";
  print ${logfile} "---\n\n";
  close $logfile;
}

sub printTree {
  my ( $vc, $path, $depth ) = @_;

  my @children = $vc->listNodes($path);
  foreach my $child (@children) {
    print '    ' x $depth;
    print $child . "\n";
    printTree( $vc, "$path $child", $depth + 1 );
  }
}

sub printTreeOrig {
  my ( $vc, $path, $depth ) = @_;

  my @children = $vc->listOrigNodes($path);
  foreach my $child (@children) {
    print '    ' x $depth;
    print $child . "\n";
    printTreeOrig( $vc, "$path $child", $depth + 1 );
  }
}

sub hasLocalWildcard {
  my $vc    = shift;
  my $orig  = shift;
  my @peers = $vc->listNodes('ipsec site-to-site peer');
  if ($orig) {
    @peers = $vc->listOrigNodes('ipsec site-to-site peer');
  }
  return 0 if ( @peers == 0 );
  foreach my $peer (@peers) {
    my $lip = $vcVPN->returnValue("ipsec site-to-site peer $peer local-ip");
    if ($orig) {
      $lip = $vcVPN->returnOrigValue("ipsec site-to-site peer $peer local-ip");
    }
    return 1 if ( $lip && $lip eq '0.0.0.0' );
  }
  return 0;
}

sub CheckIfAddressInsideNetwork {
  my ( $address, $naipNetwork ) = @_;

  if ( !defined($address) || !defined($naipNetwork) ) {
    return 0;
  }

  my $naipSM = new NetAddr::IP($address);
  if ( defined($naipSM) ) {
    my $subnetIA = $naipSM->network()->addr();
    my $naipIA = new NetAddr::IP( $subnetIA, $naipSM->masklen() );

    if ( defined($naipIA) && $naipNetwork->within($naipIA) ) {
      return 1;
    }
  }

  return 0;
}

sub get_x509 {
  my $peer = pop(@_);
  # Setup x509, based on the L2TP x509 code
  #
  ## check that proper nodes are defined.
  my $path = "vpn ipsec site-to-site peer $peer authentication x509 ";
  my $cacrt = $vcVPN->returnValue("ipsec site-to-site peer $peer authentication x509 ca-cert-file");
  vpn_die([split(' ', ($path."ca-cert-file"))],
          "$vpn_cfg_err No CA certificate for peer \"$peer\" specified.\n") if !defined($cacrt);
  my $crl = $vcVPN->returnValue("ipsec site-to-site peer $peer authentication x509 crl-file");
  my $crt = $vcVPN->returnValue("ipsec site-to-site peer $peer authentication x509 cert-file");
  vpn_die([split(' ', ($path."cert-file"))],
          "$vpn_cfg_err No Certificate for peer \"$peer\" specified.\n") if !defined($crt);
  my $key = $vcVPN->returnValue("ipsec site-to-site peer $peer authentication x509 key file");
  vpn_die([split(' ', ($path."key-file"))],
          "$vpn_cfg_err No Key for peer \"$peer\" specified.\n") if !defined($key);

  # Verify the files exist
  vpn_die([split(' ', ($path."ca-cert-file"))] , "Invalid ca-cert-file \"$cacrt\"")
    if (! -f $cacrt);
  vpn_die([split(' ', ($path."cert-file"))] , "Invalid cert-file \"$crt\"")
    if (! -f $crt);
  vpn_die([split(' ', ($path."key-file"))] , "Invalid key-file \"$key\"" )
    if (! -f $key);

  
  # Copy files to the ipsec directory
  system("cp -f $cacrt $CA_CERT_PATH/");
  vpn_die([split(' ', ($path."ca-cert-file"))] , "Cannot copy ca-cert-file \"$cacrt\"")
    if ($? >> 8);
  system("cp -f $crt $SERVER_CERT_PATH/");
  vpn_die([split(' ', ($path."cert-file"))] , "Cannot copy cert-file \"$crt\"")
    if ($? >> 8);
  system("cp -f $key $SERVER_KEY_PATH/");
  vpn_die([split(' ', ($path."key-file"))] , "Cannot copy key-file \"$key\"" )
    if ($? >> 8);

  # Handle CRL file if it is defined 
  if (defined($crl)) {
    vpn_die([split(' ', ($path."crl-file"))], "Invalid crl-file \"$crl\"")
      if (! -f $crl);
    system("cp -f $crl $CRL_PATH/");
    vpn_die([split(' ', ($path."crl-file"))], "Cannot copy crl-file \"$crl\"") 
      if ($? >> 8);
  }
  $crt =~ s/^.*(\/[^\/]+)$/${SERVER_CERT_PATH}$1/;
  my $auth_str = "\tauthby=rsasig\n";
  $auth_str .= "\tleftrsasigkey=%cert\n";
  $auth_str .= "\trightrsasigkey=%cert\n";
  $auth_str .= "\trightca=%same\n";
  $auth_str .= "\tleftcert=$crt\n";
  return $auth_str;
}

sub get_x509_secret {
  my $peer = pop(@_);
  my $key_file = $vcVPN->returnValue("ipsec site-to-site peer $peer authentication x509 key file");
  my $key_pass = $vcVPN->returnValue("ipsec site-to-site peer $peer authentication x509 key password");
  my $pstr = (defined($key_pass) ? " \"$key_pass\"" : '');
  $key_file =~ s/^.*(\/[^\/]+)$/${SERVER_KEY_PATH}$1/;
  my $str = ": RSA ${key_file}$pstr \n";
  return $str;
}

sub get_dhcp_addr {
  my ($dhcp_iface, $peer) = @_;
  vpn_die(["vpn","ipsec","site-to-site","peer",$peer,"dhcp-interface"],
    "$vpn_cfg_err The specified interface is not configured for dhcp.")
    if (!(Vyatta::Misc::is_dhcp_enabled($dhcp_iface,0)));
  my @dhcp_addr = Vyatta::Misc::getIP($dhcp_iface,4);
  my $addr = pop(@dhcp_addr);
  if (!defined($addr)){
    $addr = '';
    return $addr;
  }
  @dhcp_addr = split(/\//, $addr); 
  $addr = $dhcp_addr[0];
  return $addr;
}

sub dhcp_hook {
  my $dhcp_iface = pop(@_);
  my $str = '';
  if ($dhcp_iface > 0){
    $str =<<EOS;
#!/bin/sh
/opt/vyatta/bin/sudo-users/vyatta-ipsec-dhcp.pl --interface=\"\$interface\" --new_ip=\"\$new_ip_address\" --reason=\"\$reason\" --old_ip=\"\$old_ip_address\"
EOS
  }
  my $hook = "/etc/dhcp3/dhclient-exit-hooks.d/ipsecd";
  open my $dhcp_hook, '>', $hook
    or die "cannot open $hook";
  print ${dhcp_hook} $str;
  close $dhcp_hook;
}


# end of file