Lua userpages: Tunnels (#271)

* Lua vpn server and client pages

* Lua vpn server and client pages

* Fix reporting of daemon restart errors

* Lua olsrd-config

* Fix reversed client/server ip assignments

* Fix patterns for finding active tunnels
This commit is contained in:
Tim Wilkinson 2022-03-08 19:07:58 -08:00 committed by GitHub
parent f41fff889d
commit 922a74d574
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 2585 additions and 1136 deletions

View File

@ -1,163 +1,201 @@
#!/usr/bin/perl -w -I/www/cgi-bin
=for comment
#! /usr/bin/lua
--[[
Part of AREDN -- Used for creating Amateur Radio Emergency Data Networks
Copyright (C) 2015 Conrad Lara
See Contributors file for additional contributors
Part of AREDN -- Used for creating Amateur Radio Emergency Data Networks
Copyright (C) 2021 Tim Wilkinson
Original Perl Copyright (C) 2015 Conrad Lara
See Contributors file for additional contributors
Copyright (c) 2013 David Rivenburg et al. BroadBand-HamNet
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 3 of the License.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 3 of the License.
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 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.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional Terms:
Additional Terms:
Additional use restrictions exist on the AREDN(TM) trademark and logo.
See AREDNLicense.txt for more info.
Additional use restrictions exist on the AREDN(TM) trademark and logo.
See AREDNLicense.txt for more info.
Attributions to the AREDN Project must be retained in the source code.
If importing this code into a new or existing project attribution
to the AREDN project must be added to the source code.
Attributions to the AREDN Project must be retained in the source code.
If importing this code into a new or existing project attribution
to the AREDN project must be added to the source code.
You must not misrepresent the origin of the material contained within.
You must not misrepresent the origin of the material contained within.
Modified versions must be modified to attribute to the original source
and be marked in reasonable ways as differentiate it from the original
version
Modified versions must be modified to attribute to the original source
and be marked in reasonable ways as differentiate it from the original
version.
--]]
=cut
require("nixio")
require("aredn.utils")
require("aredn.hardware")
aredn.info = require('aredn.info')
require("uci")
# this script generates the olsrd config file
# static part comes from /etc/config/olsrd.conf
# dynamic part depends on the node configuration
-- check what config gile we are building for
local uci_conf_file
if #arg == 0 then
uci_conf_file = "olsrd"
else
uci_conf_file = arg[1]
end
use perlfunc;
use ucifunc;
use tunfunc;
if uci_conf_file == "olsrd6" then
-- we only generate entries for IPv4 at the moment
os.exit(0)
end
#Check what config file we are building for
if ( !$ARGV[0] ) {
$UCI_CONF_FILE="olsrd";
} else {
$UCI_CONF_FILE=$ARGV[0];
}
local cursor = uci.cursor()
if ( $UCI_CONF_FILE eq "olsrd6" ) {
# We only generate entries for IPv4 at moment"
exit 0;
}
local names = {}
local hosts = {}
local services = {}
local tunnels = {}
@names = @hosts = @services = @tunnels = ();
function ip_to_hostname(ip)
if ip and ip ~= "" and ip ~= "none" then
local a, b, c, d = ip:match("(.*)%.(.*)%.(.*)%.(.*)")
local revip = d .. "." .. c .. "." .. b .. "." .. a
local f = io.popen("nslookup " .. ip)
if f then
local pattern = "^" .. revip .. "%.in-addr%.arpa%s+name%s+=%s+(%S+)%.local%.mesh"
for line in f:lines()
do
local host = line:match(pattern)
if host then
f:close()
return host
end
end
f:close()
end
end
return ""
end
# canonical names for this node
# (they show up in reverse order, make the "official" name last)
push @names, $name if ($name = nvram_get("tactical"));
push @names, $name if ($name = nvram_get("node"));
-- canonical names for this node
-- (they should up in reverse order, make the official name last)
local name = aredn.info.get_nvram("tactical")
if name ~= "" then
names[#names + 1] = name
end
name = aredn.info.get_nvram("node")
if name ~= "" then
names[#names + 1] = name
end
# load the dhcp reservations when in dmz mode
chomp(my $dmz_mode = `/sbin/uci -q get aredn.\@dmz[0].mode`);
if($dmz_mode ne "0")
{
# add DNS aliases first
# (see above comment about "tactical" names)
foreach(`cat /etc/config.mesh/aliases.dmz`) {
next unless ($ip, $host) = split ' ', $_;
push @hosts, qq("$ip" "$host");
}
#($lanip, $lanmask, $lanbcast, $lannet) = get_ip4_network("eth0.0");
foreach(`cat /etc/ethers`)
{
#stop certain IP's from getting propagated over the mesh
($junk, $junk, $noprop) = split ' ', $_;
next if $noprop eq "#NOPROP";
local dmz_mode = cursor:get("aredn", "@dmz[0]", "mode")
if dmz_mode ~= "0" then
if nixio.fs.stat("/etc/config.mesh/aliases.dmz") then
for line in io.lines("/etc/config.mesh/aliases.dmz")
do
local ip, host = line:match("(.*) (.*)")
if host then
hosts[#hosts + 1] = { ip = ip, host = host }
end
end
end
if nixio.fs.stat("/etc/ethers") then
for line in io.lines("/etc/ethers")
do
local noprop = line:match(".* .*( .*)")
if noprop ~= " #NOPROP" then
local ip = line:match("[0-9a-fA-F:]+%s+([%d%.]+)")
if ip then
local host = ip_to_hostname(ip)
if host then
hosts[#hosts + 1] = { ip = ip, host = host }
end
end
end
end
end
end
next unless ($ip) = /[0-9a-f:]+\s+([\d\.]+)/i;
next unless $host = ip2hostname($ip);
push @hosts, qq("$ip" "$host");
}
}
-- add a name for the dtdlink interface
if name then
local dtdip = aredn.hardware.get_interface_ip4(aredn.hardware.get_iface_name("dtdlink"))
hosts[#hosts + 1] = { ip = dtdip, host = "dtdlink." .. name .. ".local.mesh" }
end
# Add a name for the dtdlink interface.
if ($name = nvram_get("node"))
{
my ($dtdip,$dtdmask,$dtdbcast,$dtdnet);
($dtdip, $dtdmask, $dtdbcast, $dtdnet) = get_ip4_network(get_interface("dtdlink"));
push @hosts, qq("$dtdip" "dtdlink.$name.local.mesh");
}
-- load the services
if nixio.fs.stat("/etc/config/services") then
for line in io.lines("/etc/config/services")
do
if line:match("^%w+://[%w%-%.]+:%d+(/[^|]*)?|[tu][cd]p|%w") then
services[#services + 1] = line
end
end
end
# load the services
foreach(`cat /etc/config/services 2>/dev/null`)
{
next unless /^\w+:\/\/[\w\-\.]+:\d+(\/[^\|]*)?\|(tcp|udp)\|\w/;
chomp;
push @services, $_;
}
-- load the tunnels
if nixio.fs.stat("/etc/local/mesh-firewall/02-vtund") then
local tunnum = 50
cursor:foreach("vtun", "client",
function(section)
if section.enabled == "1" then
tunnels[#tunnels + 1] = "tun" .. tunnum
tunnum = tunnum + 1
end
end
)
local maxclients = cursor:get("aredn", "@tunnel[0]", "maxclients")
if not maxclients then
maxclients = 10
end
tunnum = 50 + maxclients
cursor:foreach("vtun", "server",
function(section)
if section.enabled == "1" then
tunnels[#tunnels + 1] = "tun" .. tunnum
tunnum = tunnum + 1
end
end
)
end
# load the tunnels
my @tunnelnames = @section = ();
-- add the nameservice plugin
print()
print([[LoadPlugin "olsrd_nameservice.so.0.4"]])
print([[{]])
print([[ PlParam "sighup-pid-file" "/var/run/dnsmasq/dnsmasq.pid"]])
print([[ PlParam "interval" "30"]])
print([[ PlParam "timeout" "300"]])
print([[ PlParam "name-change-script" "touch /tmp/namechange"]])
for _, name in ipairs(names)
do
print([[ PlParam "name" "]] .. name .. [["]])
end
for _, host in ipairs(hosts)
do
print([[ PlParam "]] .. host.ip .. [[" "]] .. host.host .. [["]])
end
for _, service in ipairs(services)
do
print([[ PlParam "service" "]] .. service .. [["]])
end
print([[}]])
if (-e "/etc/local/mesh-firewall/02-vtund")
{
$tunnum=50;
push(@tunnelnames, &uci_get_names_by_sectiontype("vtun","client"));
foreach (@tunnelnames)
{
$section=&uci_get_named_section("vtun",$_);
if ($section->{enabled} eq 1)
{
push(@tunnels,"tun${tunnum}");
$tunnum++;
}
}
$tunnum=50 + &get_tunnel_maxclients();
@tunnelnames=&uci_get_names_by_sectiontype("vtun","server");
foreach (@tunnelnames)
{
$section=&uci_get_named_section("vtun",$_);
if ($section->{enabled} eq 1)
{
push(@tunnels,"tun${tunnum}");
$tunnum++;
}
}
}
# add the nameservice plugin
push @file, qq(\nLoadPlugin "olsrd_nameservice.so.0.4"\n);
push @file, qq({\n);
push @file, qq( PlParam "sighup-pid-file" "/var/run/dnsmasq/dnsmasq.pid"\n);
push @file, qq( PlParam "interval" "30"\n);
push @file, qq( PlParam "timeout" "300"\n);
push @file, qq( PlParam "name-change-script" "touch /tmp/namechange"\n);
#push @file, qq( PlParam "lat" "1"\n);
#push @file, qq( PlParam "lon" "2"\n);
#push @file, qq( PlParam "laton-file" "/var/run/latlon.js"\n);
#push @file, qq( PlParam "laton-infile" "/tmp/latlon.txt"\n);
foreach(@names) { push @file, qq( PlParam "name" "$_"\n) }
foreach(@hosts) { push @file, qq( PlParam $_\n) }
foreach(@services) { push @file, qq( PlParam "service" "$_"\n) }
push @file, qq(}\n);
# add the ACTIVE tunnel interfaces
if ( @tunnels )
{
push @file, qq(\nInterface );
foreach(@tunnels) { push @file, qq("$_" ) }
push @file, qq(\n{\n);
push @file, qq( Ip4Broadcast 255.255.255.255\n);
push @file, qq( Mode \"ether\"\n);
push @file, qq(}\n);
}
# write the file
print @file;
-- add the ACTIVE tunnel interfaces
if #tunnels > 0 then
local tuns = ""
for _, tunnel in ipairs(tunnels)
do
tuns = tuns .. " \"" .. tunnel .. "\""
end
print()
print([[Interface]] .. tuns)
print([[{]])
print([[ Ip4Broadcast 255.255.255.255]])
print([[ Mode "ether"]])
print([[}]])
end

View File

@ -0,0 +1,163 @@
#!/usr/bin/perl -w -I/www/cgi-bin
=for comment
Part of AREDN -- Used for creating Amateur Radio Emergency Data Networks
Copyright (C) 2015 Conrad Lara
See Contributors file for additional contributors
Copyright (c) 2013 David Rivenburg et al. BroadBand-HamNet
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 3 of the License.
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.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional Terms:
Additional use restrictions exist on the AREDN(TM) trademark and logo.
See AREDNLicense.txt for more info.
Attributions to the AREDN Project must be retained in the source code.
If importing this code into a new or existing project attribution
to the AREDN project must be added to the source code.
You must not misrepresent the origin of the material contained within.
Modified versions must be modified to attribute to the original source
and be marked in reasonable ways as differentiate it from the original
version.
=cut
# this script generates the olsrd config file
# static part comes from /etc/config/olsrd.conf
# dynamic part depends on the node configuration
use perlfunc;
use ucifunc;
use tunfunc;
#Check what config file we are building for
if ( !$ARGV[0] ) {
$UCI_CONF_FILE="olsrd";
} else {
$UCI_CONF_FILE=$ARGV[0];
}
if ( $UCI_CONF_FILE eq "olsrd6" ) {
# We only generate entries for IPv4 at moment"
exit 0;
}
@names = @hosts = @services = @tunnels = ();
# canonical names for this node
# (they show up in reverse order, make the "official" name last)
push @names, $name if ($name = nvram_get("tactical"));
push @names, $name if ($name = nvram_get("node"));
# load the dhcp reservations when in dmz mode
chomp(my $dmz_mode = `/sbin/uci -q get aredn.\@dmz[0].mode`);
if($dmz_mode ne "0")
{
# add DNS aliases first
# (see above comment about "tactical" names)
foreach(`cat /etc/config.mesh/aliases.dmz`) {
next unless ($ip, $host) = split ' ', $_;
push @hosts, qq("$ip" "$host");
}
#($lanip, $lanmask, $lanbcast, $lannet) = get_ip4_network("eth0.0");
foreach(`cat /etc/ethers`)
{
#stop certain IP's from getting propagated over the mesh
($junk, $junk, $noprop) = split ' ', $_;
next if $noprop eq "#NOPROP";
next unless ($ip) = /[0-9a-f:]+\s+([\d\.]+)/i;
next unless $host = ip2hostname($ip);
push @hosts, qq("$ip" "$host");
}
}
# Add a name for the dtdlink interface.
if ($name = nvram_get("node"))
{
my ($dtdip,$dtdmask,$dtdbcast,$dtdnet);
($dtdip, $dtdmask, $dtdbcast, $dtdnet) = get_ip4_network(get_interface("dtdlink"));
push @hosts, qq("$dtdip" "dtdlink.$name.local.mesh");
}
# load the services
foreach(`cat /etc/config/services 2>/dev/null`)
{
next unless /^\w+:\/\/[\w\-\.]+:\d+(\/[^\|]*)?\|(tcp|udp)\|\w/;
chomp;
push @services, $_;
}
# load the tunnels
my @tunnelnames = @section = ();
if (-e "/etc/local/mesh-firewall/02-vtund")
{
$tunnum=50;
push(@tunnelnames, &uci_get_names_by_sectiontype("vtun","client"));
foreach (@tunnelnames)
{
$section=&uci_get_named_section("vtun",$_);
if ($section->{enabled} eq 1)
{
push(@tunnels,"tun${tunnum}");
$tunnum++;
}
}
$tunnum=50 + &get_tunnel_maxclients();
@tunnelnames=&uci_get_names_by_sectiontype("vtun","server");
foreach (@tunnelnames)
{
$section=&uci_get_named_section("vtun",$_);
if ($section->{enabled} eq 1)
{
push(@tunnels,"tun${tunnum}");
$tunnum++;
}
}
}
# add the nameservice plugin
push @file, qq(\nLoadPlugin "olsrd_nameservice.so.0.4"\n);
push @file, qq({\n);
push @file, qq( PlParam "sighup-pid-file" "/var/run/dnsmasq/dnsmasq.pid"\n);
push @file, qq( PlParam "interval" "30"\n);
push @file, qq( PlParam "timeout" "300"\n);
push @file, qq( PlParam "name-change-script" "touch /tmp/namechange"\n);
#push @file, qq( PlParam "lat" "1"\n);
#push @file, qq( PlParam "lon" "2"\n);
#push @file, qq( PlParam "laton-file" "/var/run/latlon.js"\n);
#push @file, qq( PlParam "laton-infile" "/tmp/latlon.txt"\n);
foreach(@names) { push @file, qq( PlParam "name" "$_"\n) }
foreach(@hosts) { push @file, qq( PlParam $_\n) }
foreach(@services) { push @file, qq( PlParam "service" "$_"\n) }
push @file, qq(}\n);
# add the ACTIVE tunnel interfaces
if ( @tunnels )
{
push @file, qq(\nInterface );
foreach(@tunnels) { push @file, qq("$_" ) }
push @file, qq(\n{\n);
push @file, qq( Ip4Broadcast 255.255.255.255\n);
push @file, qq( Mode \"ether\"\n);
push @file, qq(}\n);
}
# write the file
print @file;

File diff suppressed because it is too large Load Diff

519
files/www/cgi-bin/vpn.pl Executable file
View File

@ -0,0 +1,519 @@
#!/usr/bin/perl
=for comment
Part of AREDN -- Used for creating Amateur Radio Emergency Data Networks
Copyright (c) 2015 Darryl Quinn
See Contributors file for additional contributors
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 3 of the License.
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.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional Terms:
Additional use restrictions exist on the AREDN(TM) trademark and logo.
See AREDNLicense.txt for more info.
Attributions to the AREDN Project must be retained in the source code.
If importing this code into a new or existing project attribution
to the AREDN project must be added to the source code.
You must not misrepresent the origin of the material contained within.
Modified versions must be modified to attribute to the original source
and be marked in reasonable ways as differentiate it from the original
version.
=cut
$debug = 0;
BEGIN {push @INC, '/www/cgi-bin'};
use perlfunc;
use ucifunc;
use tunfunc;
$VPNVER="1.1";
$config = nvram_get("config");
$node = nvram_get("node");
$node = "NOCALL" if $node eq "";
read_postdata();
#################################
# save clients from form to UCI
#################################
sub save_clients()
{
my $enabled_count=0;
for ($i=0; $i < $parms{"client_num"}; $i++) {
my $net = $parms{"client${i}_netip"};
$rc=&uci_add_named_section("vtun","client_$i","client");
# generate the clientip and serverip
my ($clientip, $serverip) = &generate_ips($net);
$rc=&uci_set_named_option("vtun","client_$i","netip",$net);
push(@cli_err,"Problem saving UCI vtun client net IP (#$i): $rc") if $rc;
$rc=&uci_set_named_option("vtun","client_$i","enabled",$parms{"client${i}_enabled"});
push(@cli_err,"Problem saving UCI vtun client enabled (#$i): $rc") if $rc;
$rc=&uci_set_named_option("vtun","client_$i","name",$parms{"client${i}_name"});
push(@cli_err,"Problem saving UCI vtun client name (#$i): $rc") if $rc;
$rc=&uci_set_named_option("vtun","client_$i","contact",$parms{"client${i}_contact"});
push(@cli_err,"Problem saving UCI vtun client contact (#$i): $rc") if $rc;
$rc=&uci_set_named_option("vtun","client_$i","passwd",$parms{"client${i}_passwd"});
push(@cli_err,"Problem saving UCI vtun client password (#$i): $rc") if $rc;
# generate the VTUN NODE name based on the node name and netip
$net=~ s/\./\-/g;
#VTUN NODE name must not be more than 23 chars long to avoid username limits!
my $vtun_node_name=substr($parms{"client${i}_name"},0,23) . "-" . $net;
$rc=&uci_set_named_option("vtun","client_$i","clientip",$clientip);
push(@cli_err,"Problem saving UCI vtun client client IP (#$i): $rc") if $rc;
$rc=&uci_set_named_option("vtun","client_$i","serverip",$serverip);
push(@cli_err,"Problem saving UCI vtun client server IP (#$i): $rc") if $rc;
$rc=&uci_set_named_option("vtun","client_$i","node",$vtun_node_name);
push(@cli_err,"Problem saving UCI vtun client name (#$i): $rc") if $rc;
$enabled_count++ if $parms{"client${i}_enabled"};
}
my $maxclients = &get_tunnel_maxclients();
push(@cli_err,"Number of clients enabled ($enabled_count) exceeds maxclients ($maxclients); only the first $enabled_count will activate.") if $enabled_count > $maxclients;
}
#################################
# save network info to UCI
#################################
sub save_network()
{
push(@cli_err,"The third octet of the network MUST be from 0 to 255") unless (($parms{server_net1}>=0) && ($parms{server_net1}<=255) && ($parms{server_net1} ne ''));
push(@cli_err,"The last octet of the network MUST be from 0 to 255") unless (($parms{server_net2}>=0) && ($parms{server_net2}<=255) && ($parms{server_net2} ne ''));
push(@cli_err,"The last octet of the network MUST be a multiple of 4 (ie. 0,4,8,12,16,...)") if ($parms{server_net2} % 4);
push(@cli_err,"Not a valid DNS name") unless (validate_fqdn($parms{dns}));
if (not @cli_err)
{
my $net=sprintf("%d.%d.%d.%d",172,31,$parms{server_net1},$parms{server_net2});
push @cli_err, "Problem saving the server network values!" if (&uci_set_indexed_option("vtun","network",0,"start",$net));
push @cli_err, "Problem saving the server DNS name!" if (&uci_set_indexed_option("vtun","network",0,"dns",$dns));
}
}
#################
# page checks
#################
if($parms{button_reboot})
{
system "/sbin/reboot";
}
if($parms{button_install})
{
install_vtun();
}
reboot_required() if($config eq "" or -e "/tmp/reboot-required");
&vpn_setup_required("vpn") unless(-e "/usr/sbin/vtund" );
#################
# If RESET, revert the UCI file
#################
if($parms{button_reset})
{
($rc,$res)=&uci_revert("vtun");
($rc,$res)=&uci_delete_option("vtun","network",0,"start");
($rc,$res)=&uci_delete_option("vtun","network",0,"dns");
$rc=&uci_commit("vtun");
}
#################
# get vtun network address
#################
@netw = ();
@netw = get_server_network_address();
$dns = get_server_dns();
#################
# If RESET or FIRST TIME, load clients/servers from file into parms
#################
if($parms{button_reset} or not $parms{reload})
{
# revert to previous state on initial load
($rc,$res)=&uci_revert("vtun");
# load clients from UCI
&get_client_info();
$parms{server_net1}=$netw[2];
$parms{server_net2}=$netw[3];
$parms{dns}=$dns;
# initialize the "add" entries to clear them
foreach $var (qw(client_add_enabled client_add_name client_add_passwd))
{
$parms{$var} = "";
$parms{$var} = "0" if($var eq 'client_add_enabled');
}
}
#################
# load clients from FORM and validate
#################
for($i =0 , @list = (); $i < $parms{client_num}; $i++) { push @list, $i }
push @list, "_add";
$client_num = 0;
foreach $val (@list)
{
foreach $var (qw(enabled name passwd netip contact))
{
$varname = "client${val}_$var";
$parms{$varname} = "0" if($val eq "enabled" and $parms{$varname} eq "");
$parms{$varname} = "" unless $parms{$varname};
$parms{$varname} =~ s/^\s+//;
$parms{$varname} =~ s/\s+$//;
if($val ne "_add")
{
if($parms{$varname} eq "" and ($var eq "enabled"))
{
$parms{$varname} = "0";
}
}
eval sprintf("\$%s = \$parms{%s}", $var, $varname);
}
# Validate ADDed values
if($val eq "_add")
{
# skip any null values on add or save
next unless ($enabled or $name or $passwd or $contact) and ($parms{client_add} or $parms{button_save});
} # no delete capabilities as net renumbering is not allowed
if($val eq "_add" and $parms{button_save})
{
push @cli_err, "$val this client must be added or cleared out before saving changes";
next;
}
# password MUST be alphanumeric (no special chars)
push @cli_err, "The password cannot contain non-alphanumeric characters (#$client_num)" if ($passwd =~ m/[^a-zA-Z0-9@]/);
push @cli_err, "The password must contain at least one alphabetic character (#$client_num)" if ($passwd !~ /\D/);
push @cli_err, "A client name is required" if($name eq "");
push @cli_err, "A client password is required" if($passwd eq "");
next if $val eq "_add" and @cli_err and $cli_err[-1] =~ /^$val /;
$parms{"client${client_num}_enabled"} = $enabled;
$parms{"client${client_num}_name"} = uc $name;
$parms{"client${client_num}_passwd"} = $passwd;
$parms{"client${client_num}_netip"} = $netip;
# Commit the data for this client
$client_num++;
# Clear out the ADD values
if($val eq "_add")
{
foreach $var (qw(net enabled name passwd netip contact))
{
$parms{"client_add_${var}"} = "";
}
}
}
$parms{client_num} = $client_num;
#################
# SAVE the server network numbers and dns into the UCI
#################
$netw[2]=$parms{server_net1};
$netw[3]=$parms{server_net2};
$dns=$parms{dns};
$rc=save_network();
#################
# SAVE the clients
#################
$rc=save_clients();
#################
# save configuration (commit)
#################
if($parms{button_save} and not @cli_err)
{
if (&uci_commit("vtun"))
{
push(@errors,"Problem committing UCI vtun");
}
&uci_clone("vtun");
unless($debug == 3)
{
# Regenerate olsrd files and restart olsrd
push(@errors,"Problem restarting olsrd") if system "/etc/init.d/olsrd restart > /dev/null 2>&1";
push(@errors,"Problem restaring vtundsrv") if system "/etc/init.d/vtundsrv restart > /dev/null 2>&1";
# delay to allow clients to connect and have an accurate "cloud" status
sleep 5;
}
}
@active_tun=&get_active_tun();
######################################################################################
# generate the page
######################################################################################
http_header() unless $debug == 2;
html_header("$node setup", 1);
print "<body><center>\n";
alert_banner();
print "<form id=vpn method=post action=/cgi-bin/vpn.pl enctype='multipart/form-data'>\n" unless $debug == 2;
print "<form method=post action=test>\n" if $debug == 2;
print "<table width=790>\n";
#################
# Navigation bar
#################
print "<tr><td>\n";
navbar("vpn");
print "</td></tr>\n";
#################
# control buttons
#################
print "<tr><td align=center>";
print "<a href='/help.html#vpn' target='_blank'>Help</a>";
print "&nbsp;&nbsp;&nbsp;\n";
print "<input type=submit name=button_save value='Save Changes' title='Save and use these settings now (takes about 20 seconds)'>&nbsp;\n";
print "<input type=submit name=button_reset value='Reset Values' title='Revert to the last saved settings'>&nbsp;\n";
print "<input type=submit name=button_refresh value='Refresh' title='Refresh this page'>&nbsp;\n";
print "<tr><td>&nbsp;</td></tr>\n";
push @hidden, "<input type=hidden name=reload value=1></td></tr>";
#################
# messages
#################
if(@cli_err)
{
print "<tr><td align=center><b>ERROR:<br>";
foreach(@cli_err) { print "$_<br>" }
print "</b></td></tr>\n";
}
if($parms{button_save})
{
if(@cli_err)
{
print "<tr><td align=center><b>Configuration NOT saved!</b></td></tr>\n";
#}
#elsif(@errors)
#{
#print "<tr><td align=center><b>Configuration saved, however:<br>";
foreach(@errors) { print "$_<br>" }
print "</b></td></tr>\n";
}
else
{
print "<tr><td align=center><b>Configuration saved and is now active.</b></td></tr>\n";
}
print "<tr><td>&nbsp;</td></tr>\n";
}
#################
# everything else
#################
if($config eq "mesh")
{
print "<tr><td align=center valign=top>\n";
&print_vpn_clients();
print "</td></tr>\n";
print "<tr><td><hr></td></tr>\n";
}
print "</table>\n";
print "<p style='font-size:8px'>Tunnel v${VPNVER}</p>";
push @hidden, "<input type=hidden name=client_num value=$parms{client_num}>";
#################
# add hidden form fields
#################
foreach(@hidden) { print "$_\n" }
#################
# close the form
#################
print "</form></center>\n";
show_debug_info();
#################
# close the html
#################
page_footer();
print "</body></html>\n";
exit;
##################
# page subsections
##################
######################################################
# List the clients allowed to connect to this server
######################################################
sub print_vpn_clients()
{
print "<table cellpadding=0 cellspacing=0>";
print "<br /><tr class=tun_network_row><td colspan=6 align=center valign=top>Tunnel Server Network: ";
printf("%d.%d.",$netw[0],$netw[1]);
print "<input type='text' name='server_net1' size='3' maxlen='3' value='$netw[2]' onChange='form.submit()' title='from 0-255' >";
print ".";
print "<input type='text' name='server_net2' size='3' maxlen='3' value='$netw[3]' onChange='form.submit()' title='from 0-255 in multiples of 4. (ie. 0,4,8,12,16...252)' >";
print "<br /><hr>Tunnel Server DNS Name: ";
print "<input type='text' name='dns' size='30' value='$dns' onChange='form.submit()' ></td></tr>";
print "</table>";
#print "<hr />";
print "<table cellpadding=0 cellspacing=0>";
print "<tr><th colspan=6 align=center valign=top>&nbsp;</th></tr>\n";
print "<tr class=tun_client_row>";
print "<tr><th colspan=6>Allow the following clients to connect to this server:</th></tr>\n";
print "<tr><th colspan=6><hr></th></tr>\n";
print "<tr><th>Enabled?</th><th>Client</th><th>Pwd</th><th>Net</th><th>Active&nbsp;</td><th>Action</th></tr>\n";
for($i = 0, @list = (); $i < $parms{client_num}; ++$i) { push @list, $i };
push @list, "_add" unless($parms{client_num} >= &get_tunnel_maxclients());
$cnum=0;
foreach $val (@list)
{
foreach $var (qw(enabled name passwd contact))
{
eval sprintf("\$%s = \$parms{client%s_%s}", $var, $val, $var);
}
print "<tr class=tun_client_add_row><td height=10></td></tr>\n" if $val eq "_add" and scalar(@list) > 1;
print "<tr class='tun_client_list2 tun_client_row'>";
print "<td class='tun_client_center_item' rowspan='2'>";
# Required to be first, so, if the checkbox is cleared, a value will still POST
print "<input type='hidden' name='client${val}_enabled' value='0'>" unless($val eq "_add");
print "<input type='checkbox' name='client${val}_enabled' value='1'";
print " onChange='form.submit()'" unless $val eq "_add";
print " checked='checked'" if $enabled;
print " title='enable this client'></td>";
print "<td><input type=text size=40 name=client${val}_name value='$name'";
print " onChange='form.submit()'" unless $val eq "_add";
# print " disabled" unless $val eq "_add";
print " title='client name'></td>";
print "<td><input type=text size=25 name=client${val}_passwd value='$passwd' ";
print " onChange='form.submit()'" unless $val eq "_add";
print " title='client password'";
#print " disabled" unless $val eq "_add";
print "></td>";
# handle rollover of netw[3]
if($netw[3]+($cnum * 4) > 252) {
$netw[2]++;
$netw[3] = 0;
$net=0;
$cnum=0;
} else {
$net=$cnum;
}
if($val eq "_add") { $lastnet=$netw[3]+(($net) * 4); }
else { $lastnet=$netw[3]+($net * 4); }
$fullnet=sprintf("%d.%d.%d.%d",$netw[0],$netw[1],$netw[2],$lastnet);
print "<td rowspan='2' class='tun_client_center_item'>&nbsp;$fullnet";
print "<input type=hidden name=client${val}_netip value='$fullnet'/></td>";
print "<td rowspan='2' class='tun_client_center_item' align=center>&nbsp;";
if (&is_tunnel_active($fullnet,@active_tun) && ($val ne "_add")) {
print "<img class='tun_client_active_img' src='/connected.png' title='Connected' />";
} else {
print "<img class='tun_client_inactive_img' src='/disconnected.png' title='Not connected' />";
}
print "</td>";
print "<td rowspan='2' class='tun_client_center_item'><input type=submit name=client_add value=Add title='Add this client'>" if($val eq "_add");
print "</td>";
print "<td rowspan='2' class='tun_client_center_item tun_client_mailto'><a href='mailto:?subject=AREDN%20Tunnel%20Connection&body=Your%20connection%20details:%0D%0AName:%20$name%0D%0APassword:%20$passwd%0D%0ANetwork:%20$fullnet%0D%0AServer%20address:%20$dns' target='_blank'><img class='tun_client_mailto_img' src='/email.png' title='Email details' /></a></td>" unless($val eq "_add");
#contact info for the tunnel
print "</tr>";
print "<tr class='tun_client_list1 tun_client_row tun_loading_css_comment'><td colspan='2' align='right'>Contact Info/Comment (Optional): <input type=text maxlength='50' size=40 name=client${val}_contact value='$contact'";
print " onChange='form.submit()'" unless ($val eq "_add" || $val eq "");
print " title='client contact info'></td>";
print "</tr>\n";
# display any errors
while(@cli_err and $cli_err[0] =~ /^$val /)
{
$err = shift @cli_err;
$err =~ s/^\S+ //;
print "<tr class=tun_client_error_row><th colspan=4>$err</th></tr>\n";
}
#push @hidden, "<input type='hidden' name='client${val}_enable' value='0'>" unless($val eq "_add");
print "<tr><td colspan=4 height=4></td></tr>\n";
$cnum++;
}
print "</table>\n";
}
#################################
# load client info from UCI
#################################
sub get_client_info()
{
my @clients=&uci_get_names_by_sectiontype("vtun","client");
my $c=0;
foreach (@clients)
{
my $myclient={};
$myclient=&uci_get_named_section("vtun",$_);
foreach $var (qw(enabled name passwd netip contact))
{
$parms{"client${c}_$var"} = $myclient->{$var};
$parms{"client${c}_$var"} = "0" if($parms{"client${c}_$var"} eq "");
$myclient->{$var} = "";
}
$c++;
}
$parms{client_num} = scalar(@clients);
}
sub DEBUGEXIT()
{
my ($text) = @_;
http_header();
html_header("$node setup", 1);
print "DEBUG-";
print $text;
print "</body>";
exit;
}

File diff suppressed because it is too large Load Diff

479
files/www/cgi-bin/vpnc.pl Executable file
View File

@ -0,0 +1,479 @@
#!/usr/bin/perl
=for comment
Part of AREDN -- Used for creating Amateur Radio Emergency Data Networks
Copyright (c) 2015 Darryl Quinn
See Contributors file for additional contributors
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 3 of the License.
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.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional Terms:
Additional use restrictions exist on the AREDN(TM) trademark and logo.
See AREDNLicense.txt for more info.
Attributions to the AREDN Project must be retained in the source code.
If importing this code into a new or existing project attribution
to the AREDN project must be added to the source code.
You must not misrepresent the origin of the material contained within.
Modified versions must be modified to attribute to the original source
and be marked in reasonable ways as differentiate it from the original
version.
=cut
$debug = 0;
BEGIN {push @INC, '/www/cgi-bin'};
use perlfunc;
use ucifunc;
use tunfunc;
$VPNVER="1.0";
$config = nvram_get("config");
$node = nvram_get("node");
$node = "NOCALL" if $node eq "";
#truncate node name down to 23 chars (max) to avoid vtun issues
#this becomes the vtun "username"
$node = substr($node,0,23);
read_postdata();
#################################
# save server connections from form to UCI
#################################
sub save_connections()
{
my $enabled_count=0;
for ($i=0; $i < $parms{"conn_num"}; $i++) {
my $net = $parms{"conn${i}_netip"};
$rc=&uci_add_named_section("vtun","server_$i","server");
# generate the clientip and serverip
my ($clientip, $serverip) = &generate_ips($net);
# generate the VTUN NODE name based on the node name and netip
$net=~ s/\./\-/g;
my $vtun_node_name=uc "$node-$net";
$rc=&uci_set_named_option("vtun","server_$i","clientip",$clientip);
push(@conn_err,"Problem saving UCI vtun connection client IP (#$i)") if $rc;
$rc=&uci_set_named_option("vtun","server_$i","serverip",$serverip);
push(@conn_err,"Problem saving UCI vtun connection server IP (#$i)") if $rc;
$rc=&uci_set_named_option("vtun","server_$i","node",$vtun_node_name);
push(@conn_err,"Problem saving UCI vtun connection name (#$i)") if $rc;
$rc=&uci_set_named_option("vtun","server_$i","contact",$contact);
push(@conn_err,"Problem saving UCI vtun contact info (#$i)") if $rc;
foreach $var (qw(enabled host passwd netip contact))
{
$rc=&uci_set_named_option("vtun","server_$i",$var,$parms{"conn${i}_$var"});
push(@conn_err,"Problem saving UCI vtun connection (#$i)") if $rc;
}
$enabled_count++ if $parms{"conn${i}_enabled"};
}
my $maxservers = &get_tunnel_maxservers();
push(@conn_err,"Number of servers enabled ($enabled_count) exceeds maxservers ($maxservers); only the first $maxservers will activate.") if $enabled_count > $maxservers;
}
#################
# page checks
#################
if($parms{button_reboot})
{
system "/sbin/reboot";
}
if($parms{button_install})
{
install_vtun();
}
reboot_required() if($config eq "" or -e "/tmp/reboot-required");
&vpn_setup_required("vpnc") unless(-e "/usr/sbin/vtund" );
#################
# If RESET, revert the UCI file
#################
if($parms{button_reset})
{
($rc,$res)=&uci_revert("vtun");
$rc=&uci_commit("vtun");
}
#################
# HANDLE connection deletes
#################
for($i = 0; $i < 10; $i++)
{
$varname="conn${i}_del";
if($parms{$varname})
{
&uci_delete_named_section("vtun","server_${i}");
for($x = $i+1; $x < 10; $x++)
{
$y=$x-1;
&uci_rename_named_section("vtun","server_$x","server_${y}");
}
}
}
#################
# If RESET or FIRST TIME, load servers into parms
#################
if($parms{button_reset} or not $parms{reload})
{
# revert to previous state on initial load
($rc,$res)=&uci_revert("vtun");
# load servers from UCI
&get_connection_info();
# initialize the "add" entries to clear them
foreach $var (qw(enabled host passwd netip contact))
{
$varname = "conn${val}_$var";
$parms{$varname} = "";
$parms{$varname} = "" if($var eq 'enabled');
}
}
#################
# load connections from FORM and validate
#################
for($i =0 , @list = (); $i < $parms{conn_num}; $i++) { push @list, $i }
push @list, "_add";
$conn_num = 0;
foreach $val (@list)
{
foreach $var (qw(enabled host passwd netip contact))
{
$varname = "conn${val}_$var";
$parms{$varname} = "0" if($val eq "enabled" and $parms{$varname} eq "");
$parms{$varname} = "" unless $parms{$varname};
$parms{$varname} =~ s/^\s+//;
$parms{$varname} =~ s/\s+$//;
if($val ne "_add")
{
if($parms{$varname} eq "" and ($var eq "enabled"))
{
$parms{$varname} = "0";
}
}
eval sprintf("\$%s = \$parms{%s}", $var, $varname);
}
# Validate ADDed values
if($val eq "_add") { next unless ($enabled or $host or $passwd or $netip or $contact) and ($parms{conn_add} or $parms{button_save}) }
else { next if $parms{"conn${val}_del"} }
# Validate password is vtun compliant
# TODO
if($val eq "_add" and $parms{button_save})
{
push @conn_err, "$val this connection must be added or cleared out before saving changes";
next;
}
# password MUST be alphanumeric (no special chars)
push @conn_err, "The password cannot contain non-alphanumeric characters (#$conn_num)" if ($passwd =~ m/[^a-zA-Z0-9@\-]/);
push @conn_err, "A connection server is required" if($host eq "");
push @conn_err, "A connection password is required" if($passwd eq "");
push @conn_err, "A connection network IP is required" if($netip eq "");
next if $val eq "_add" and @conn_err and $conn_err[-1] =~ /^$val /;
$parms{"conn${conn_num}_enabled"} = $enabled;
$parms{"conn${conn_num}_host"} = $host;
$parms{"conn${conn_num}_passwd"} = $passwd;
$parms{"conn${conn_num}_netip"} = $netip;
$parms{"conn${conn_num}_contact"} = $contact;
# Commit the data for this connection
$conn_num++;
# Clear out the ADD values
if($val eq "_add")
{
foreach $var (qw(enabled host passwd netip contact))
{
$parms{"conn_add_${var}"} = "";
}
}
}
$parms{conn_num} = $conn_num;
#################
# SAVE the connections
#################
$rc=save_connections();
#################
# SAVE the connections the UCI vtun file
#################
if($parms{button_save} and not @conn_err)
{
if (&uci_commit("vtun"))
{
push(@errors,"Problem committing UCI vtun");
}
&uci_clone("vtun");
unless($debug == 3)
{
# Regenerate olsrd files and restart olsrd
push(@errors,"Problem restarting olsrd") if system "/etc/init.d/olsrd restart > /dev/null 2>&1";
push(@errors,"Problem restaring vtund") if system "/etc/init.d/vtund restart > /dev/null 2>&1";
sleep 5;
}
}
@active_tun=&get_active_tun();
######################################################################################
# generate the page
######################################################################################
http_header() unless $debug == 2;
html_header("$node setup", 1);
print "<body><center>\n";
alert_banner();
print "<form method=post action=/cgi-bin/vpnc.pl enctype='multipart/form-data'>\n" unless $debug == 2;
print "<form method=post action=test>\n" if $debug == 2;
print "<table width=790>\n";
#################
# Navigation bar
#################
print "<tr><td>\n";
navbar("vpnc");
print "</td></tr>\n";
#################
# control buttons
#################
print "<tr><td align=center>";
print "<a href='/help.html#vpn' target='_blank'>Help</a>";
print "&nbsp;&nbsp;&nbsp;\n";
print "<input type=submit name=button_save value='Save Changes' title='Save and use these settings now (takes about 20 seconds)'>&nbsp;\n";
print "<input type=submit name=button_reset value='Reset Values' title='Revert to the last saved settings'>&nbsp;\n";
print "<input type=submit name=button_refresh value='Refresh' title='Refresh this page'>&nbsp;\n";
print "<tr><td>&nbsp;</td></tr>\n";
push @hidden, "<input type=hidden name=reload value=1></td></tr>";
#################
# messages
#################
if(@conn_err)
{
print "<tr><td align=center><b>ERROR:<br>";
foreach(@conn_err) { print "$_<br>" }
print "</b></td></tr>\n";
}
if($parms{button_save})
{
if(@conn_err)
{
print "<tr><td align=center><b>Configuration NOT saved!</b></td></tr>\n";
}
elsif(@errors)
{
print "<tr><td align=center><b>Configuration saved, however:<br>";
foreach(@errors) { print "$_<br>" }
print "</b></td></tr>\n";
}
else
{
print "<tr><td align=center><b>Configuration saved and is now active.</b></td></tr>\n";
}
print "<tr><td>&nbsp;</td></tr>\n";
}
#################
# everything else
#################
if($config eq "mesh")
{
print "<tr><td align=center valign=top>\n";
&print_vpn_connections();
print "</td></tr>\n";
print "<tr><td><hr></td></tr>\n";
}
print "</table>\n";
print "<p style='font-size:8px'>VPN v${VPNVER}</p>";
push @hidden, "<input type=hidden name=conn_num value=$parms{conn_num}>";
#################
# add hidden form fields
#################
foreach(@hidden) { print "$_\n" }
#################
# close the form
#################
print "</form></center>\n";
show_debug_info();
#################
# close the html
#################
page_footer();
print "</body></html>\n";
exit;
##################
# page subsections
##################
######################################################
# List the connections to be made from this client
######################################################
sub print_vpn_connections()
{
print "<table id=connection_section cellpadding=0 cellspacing=0>";
print "<tr><th colspan=6>Connect this node to the following servers:</th></tr>";
print "<tr><th colspan=6><hr></th></tr>\n";
print "<tr><th>Enabled?</th><th>Server</th><th>Pwd</th><th>Network</th><th>Active&nbsp;</th><th>Action</th></tr>\n";
for($i = 0, @list = (); $i < $parms{conn_num}; $i++) { push @list, $i };
push @list, "_add" unless($parms{conn_num} >= &get_tunnel_maxservers());
$cnum=0;
foreach $val (@list)
{
foreach $var (qw(enabled host passwd netip contact))
{
eval sprintf("\$%s = \$parms{conn%s_%s}", $var, $val, $var);
}
print "<tr><td height=10></td></tr>\n" if $val eq "_add" and scalar(@list) > 1;
print "<tr class='tun_client_list2 tun_client_row'>";
print "<td class='tun_client_center_item' rowspan='2'>";
# Required to be first, so, if the checkbox is cleared, a value will still POST
print "<input type='hidden' name='conn${val}_enabled' value='0'>" unless($val eq "_add");
print "<input type='checkbox' name='conn${val}_enabled' value='1'";
print " onChange='form.submit()'" unless $val eq "_add";
print " checked='checked'" if $enabled;
#print " disabled" unless $val eq "_add";
print " title='enable this connection'></td>";
print "<td><input type=text size=25 name=conn${val}_host value='$host'";
print " onChange='form.submit()'" unless $val eq "_add";
# print " disabled" unless $val eq "_add";
print " title='connection name'></td>";
print "<td><input type=text size=20 name=conn${val}_passwd value='$passwd' ";
print " onChange='form.submit()'" unless $val eq "_add";
print " title='connection password'";
#print " disabled" unless $val eq "_add";
print "></td>";
print "<td><input type=text size=14 name=conn${val}_netip value='$netip'";
print " onChange='form.submit()'" unless $val eq "_add";
# print " disabled" unless $val eq "_add";
print " title='connection network'></td>";
print "</td>";
print "<td class='tun_client_center_item' rowspan='2'>&nbsp;";
if (&is_tunnel_active($netip,@active_tun) && ($val ne "_add")) {
print "<img class='tun_client_active_img' src='/connected.png' title='Connected' />";
} else {
print "<img class='tun_client_inactive_img' src='/disconnected.png' title='Not connected' />" if ($val ne "_add");
}
print "</td>";
print "<td class='tun_client_center_item' rowspan='2'>&nbsp;";
print "<input type=submit name=";
if($val eq "_add") { print "conn_add value=Add title='Add this connection'" }
else { print "conn${val}_del value=Del title='Delete this connection'" }
print "></td>";
#contact info for this tunnel
print "</tr>\n";
print "<tr class='tun_client_list1 tun_client_row tun_loading_css_comment'><td colspan='3' align='right'>Contact Info/Comment (Optional): <input type=text maxlength='50' size=40 name=conn${val}_contact value='$contact'";
print " onChange='form.submit()'" unless ($val eq "_add" || $val eq "");
print " title='client contact info'></td>";
print "</tr>\n";
# display any errors
while(@conn_err and $conn_err[0] =~ /^$val /)
{
$err = shift @conn_err;
$err =~ s/^\S+ //;
print "<tr><th colspan=4>$err</th></tr>\n";
}
#push @hidden, "<input type='hidden' name='client${val}_enable' value='0'>" unless($val eq "_add");
print "<tr><td colspan=6 height=4></td></tr>\n";
$cnum++;
}
print "</table>\n";
}
#################################
# load server connection info from UCI
#################################
sub get_connection_info()
{
my @connections=&uci_get_names_by_sectiontype("vtun","server");
my $c=0;
foreach (@connections)
{
my $myconn={};
$myconn=&uci_get_named_section("vtun",$_);
foreach $var (qw(enabled host passwd netip contact))
{
$parms{"conn${c}_$var"} = $myconn->{$var};
$parms{"conn${c}_$var"} = "0" if($parms{"conn${c}_$var"} eq "");
$myconn->{$var} = "";
}
$c++;
}
$parms{conn_num} = scalar(@connections);
}
sub DEBUGEXIT()
{
my ($text) = @_;
http_header();
html_header("$node setup", 1);
print "DEBUG[";
print $text;
print "]</body>";
exit;
}