mirror of https://github.com/dswd/vpncloud.git
Compare commits
5 Commits
ecebd2aab8
...
2955a80af4
Author | SHA1 | Date |
---|---|---|
Dennis Schwerdel | 2955a80af4 | |
Dennis Schwerdel | 38c3ba1177 | |
Dennis Schwerdel | 0cffea7017 | |
Dennis Schwerdel | 7abeea1f95 | |
Dennis Schwerdel | 29630ab763 |
|
@ -27,6 +27,7 @@ mkdir -p %{buildroot}/lib/systemd/system
|
|||
mkdir -p %{buildroot}/usr/share/man/man1
|
||||
cp %{buildroot}/../../../../../assets/example.net.disabled %{buildroot}/etc/vpncloud/example.net.disabled
|
||||
cp %{buildroot}/../../../../../assets/vpncloud@.service %{buildroot}/lib/systemd/system/vpncloud@.service
|
||||
cp %{buildroot}/../../../../../assets/vpncloud-wsproxy.service %{buildroot}/lib/systemd/system/vpncloud-wsproxy.service
|
||||
cp %{buildroot}/../../../../../target/vpncloud.1.gz %{buildroot}/usr/share/man/man1/vpncloud.1.gz
|
||||
cp -a * %{buildroot}
|
||||
|
||||
|
@ -38,6 +39,7 @@ rm -rf %{buildroot}
|
|||
/etc/vpncloud/example.net.disabled
|
||||
/usr/bin/vpncloud
|
||||
/lib/systemd/system/vpncloud@.service
|
||||
/lib/systemd/system/vpncloud-wsproxy.service
|
||||
/usr/share/man/man1/vpncloud.1.gz
|
||||
|
||||
%defattr(-,root,root,-)
|
||||
|
|
|
@ -374,6 +374,12 @@ version = "1.3.5"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "615caabe2c3160b313d52ccc905335f4ed5f10881dd63dc5699d47e90be85691"
|
||||
|
||||
[[package]]
|
||||
name = "iai"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "71a816c97c42258aa5834d07590b718b4c9a598944cd39a52dc25b351185d678"
|
||||
|
||||
[[package]]
|
||||
name = "idna"
|
||||
version = "0.2.1"
|
||||
|
@ -1225,6 +1231,7 @@ dependencies = [
|
|||
"criterion",
|
||||
"daemonize",
|
||||
"fnv",
|
||||
"iai",
|
||||
"igd",
|
||||
"libc",
|
||||
"log",
|
||||
|
|
|
@ -35,6 +35,7 @@ url = { version = "2.2", optional = true }
|
|||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
criterion = { version = "0.3", features = ["html_reports"] }
|
||||
iai = "0.1"
|
||||
|
||||
[features]
|
||||
default = ["nat", "websocket"]
|
||||
|
@ -42,7 +43,11 @@ nat = ["igd"]
|
|||
websocket = ["tungstenite", "url"]
|
||||
|
||||
[[bench]]
|
||||
name = "bench"
|
||||
name = "criterion"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "valgrind"
|
||||
harness = false
|
||||
|
||||
[profile.release]
|
||||
|
@ -69,6 +74,7 @@ assets = [
|
|||
["target/release/vpncloud", "/usr/bin/vpncloud", "755"],
|
||||
["assets/example.net.disabled", "/etc/vpncloud/example.net.disabled", "600"],
|
||||
["assets/vpncloud@.service", "/lib/systemd/system/vpncloud@.service", "644"],
|
||||
["assets/vpncloud-wsproxy.service", "/lib/systemd/system/vpncloud-wsproxy.service", "644"],
|
||||
["target/vpncloud.1.gz", "/usr/share/man/man1/vpncloud.1.gz", "644"]
|
||||
]
|
||||
|
||||
|
|
701
LICENSE.md
701
LICENSE.md
File diff suppressed because it is too large
Load Diff
|
@ -1,140 +1,82 @@
|
|||
# This configuration file uses the YAML format.
|
||||
|
||||
# This configuration can be enabled/disabled and controlled by adding the
|
||||
# network to `/etc/default/vpncloud` and starting/stopping it via
|
||||
# `/etc/init.d/vpncloud start/stop` on non-systemd systems and via
|
||||
# `systemctl enable/disable vpncloud@NAME` and
|
||||
# `service vpncloud@NAME start/stop` on systemd systems.
|
||||
# ~ means "no value" (i.e. "default value")
|
||||
# Replace it by a value and put quotes (") around values with special characters
|
||||
# List items start with a dash and a space (- )
|
||||
# Note that the whitespace before the settings names is important for the file structure
|
||||
|
||||
|
||||
# The port number or ip:port on which to listen for data.
|
||||
# Note: Every VPN needs a different port number.
|
||||
listen: 3210
|
||||
listen: 3210 # The port number or ip:port on which to listen for data.
|
||||
|
||||
# Address of a peer to connect to. The address should be in the form
|
||||
# `addr:port`. If the node is not started, the connection will be retried
|
||||
# periodically. This parameter can be repeated to connect to multiple peers.
|
||||
# Note: Several entries can be separated by spaces.
|
||||
peers:
|
||||
# - node2.example.com:3210
|
||||
# - node3.example.com:3210
|
||||
peers: # Address of a peer to connect to.
|
||||
# The address should be in the form `addr:port`.
|
||||
# Put [] for an empty list
|
||||
- node2.example.com:3210
|
||||
- node3.example.com:3210
|
||||
|
||||
# Peer timeout in seconds. The peers will exchange information periodically
|
||||
# and drop peers that are silent for this period of time.
|
||||
peer-timeout: 300
|
||||
crypto: # Crypto settings
|
||||
password: ~ # <-- CHANGE # A password to encrypt the VPN data.
|
||||
private-key: ~ # Private key (alternative to password)
|
||||
public-key: ~ # Public key (alternative to password)
|
||||
trusted-keys: [] # Trusted keys (alternative to password)
|
||||
# Replace [] with list of keys
|
||||
|
||||
# Switch table entry timeout in seconds. This parameter is only used in switch
|
||||
# mode. Addresses that have not been seen for the given period of time will
|
||||
# be forgot.
|
||||
switch-timeout: 300
|
||||
ip: ~ # <-- CHANGE # An IP address to set on the device, e.g. 10.0.0.1
|
||||
# Must be different for every node on the VPN
|
||||
|
||||
|
||||
# Crypto settings
|
||||
#crypto:
|
||||
# ------------------ Advanced features ahead --------------------
|
||||
|
||||
# An optional password to encrypt the VPN data.
|
||||
#password: ""
|
||||
auto-claim: true # Whether to automatically claim the configured IP on tun devices
|
||||
|
||||
# Private key
|
||||
#private-key: ""
|
||||
|
||||
# Public key
|
||||
#public-key: ""
|
||||
|
||||
# Trusted keys
|
||||
#trusted-keys:
|
||||
|
||||
# Supported algorithms. Subset of "aes128", "aes256", "chacha20", and
|
||||
# "plain" where "plain" means unencrypted.
|
||||
#algorithms:
|
||||
|
||||
|
||||
# Device settings
|
||||
device:
|
||||
|
||||
# Name of the virtual device. Any `%d` will be filled with a free number.
|
||||
name: "vpncloud%d"
|
||||
|
||||
# Set the type of network. There are two options: **tap** devices process
|
||||
# Ethernet frames **tun** devices process IP packets. [default: `tun`]
|
||||
type: tun
|
||||
|
||||
# The path of the /dev/net/tun device. Only change if you need to.
|
||||
#path: /dev/net/tun
|
||||
|
||||
# Whether to fix detected rp-filter problems
|
||||
fix-rp-filter: false
|
||||
|
||||
|
||||
# The mode of the VPN. The VPN can like a router, a switch or a hub. A **hub**
|
||||
# will send all data always to all peers. A **switch** will learn addresses
|
||||
# from incoming data and only send data to all peers when the address is
|
||||
# unknown. A **router** will send data according to known subnets of the
|
||||
# peers and ignore them otherwise. The **normal** mode is switch for tap
|
||||
# devices and router for tun devices. [default: `normal`]
|
||||
mode: normal
|
||||
|
||||
|
||||
# The local subnets to use. This parameter should be in the form
|
||||
# `address/prefixlen` where address is an IPv4 address, an IPv6 address, or a
|
||||
# MAC address. The prefix length is the number of significant front bits that
|
||||
# distinguish the subnet from other subnets. Example: `10.1.1.0/24`.
|
||||
# Note: Several entries can be separated by spaces.
|
||||
#claims:
|
||||
claims: # The local subnets to use. This parameter should be in the form
|
||||
# `address/prefixlen` where address is an IPv4 address, an IPv6 address, or a
|
||||
# MAC address. The prefix length is the number of significant front bits that
|
||||
# distinguish the subnet from other subnets.
|
||||
# - 10.1.1.0/24
|
||||
|
||||
# Whether to automatically claim the configured IP on tun devices
|
||||
auto-claim: true
|
||||
ifup: ~ # Command to setup the interface. Use $IFNAME for interface name.
|
||||
ifdown: ~ # Command to tear down the interface. Use $IFNAME for interface name.
|
||||
|
||||
device: # Device settings
|
||||
name: "vpncloud%d" # Name of the virtual device. Any `%d` will be filled with a free number.
|
||||
type: tun # Set the type of network. There are two options: **tap** devices process
|
||||
# Ethernet frames **tun** devices process IP packets. [default: `tun`]
|
||||
path: "/dev/net/tun" # Path of the tun device
|
||||
fix-rp-filter: false # Whether to fix detected rp-filter problems
|
||||
|
||||
mode: normal # Mode to run in, "normal", "hub", "switch", or "router" (see manpage)
|
||||
|
||||
port-forwarding: true # Try to map a port on the router
|
||||
|
||||
switch-timeout: 300 # Switch timeout in seconds (switch mode only)
|
||||
|
||||
peer-timeout: 300 # Peer timeout in seconds
|
||||
keepalive: ~ # Keepalive interval in seconds
|
||||
|
||||
beacon: # Beacon settings
|
||||
store: ~ # File or command (prefix: "|") to use for storing beacons
|
||||
load: ~ # File or command (prefix: "|") to use for loading beacons
|
||||
interval: 3600 # How often to load and store beacons (in seconds)
|
||||
password: ~ # Password to encrypt beacon data with
|
||||
|
||||
statsd: # Statsd settings
|
||||
server: ~ # Statsd server name:port
|
||||
prefix: ~ # Prefix to use for stats keys
|
||||
|
||||
pid-file: ~ # Store the process id in this file when running in the background
|
||||
stats-file: ~ # Periodically write statistics on peers and current traffic to the given file
|
||||
|
||||
hook: ~ # Hook script to run for every event
|
||||
hooks: {} # Multiple hook scripts to run for specific events
|
||||
|
||||
|
||||
# An IP address to set on the device
|
||||
#ip: ""
|
||||
|
||||
# A command to setup the network interface. The command will be run (as
|
||||
# parameter to `sh -c`) when the device has been created to configure it.
|
||||
# The name of the allocated device will be available via the environment
|
||||
# variable `IFNAME`.
|
||||
#ifup: ""
|
||||
|
||||
# A command to bring down the network interface. The command will be run (as
|
||||
# parameter to `sh -c`) to remove any configuration from the device.
|
||||
# The name of the allocated device will be available via the environment
|
||||
# variable `IFNAME`.
|
||||
#ifdown: ""
|
||||
|
||||
# Store the process id in this file when running in the background. If set,
|
||||
# the given file will be created containing the process id of the new
|
||||
# background process. This option is only used when running in background.
|
||||
#pid_file: ""
|
||||
|
||||
# Change the user and/or group of the process once all the setup has been
|
||||
# done and before spawning the background process. This option is only used
|
||||
# when running in background.
|
||||
#user: ""
|
||||
#group: ""
|
||||
|
||||
|
||||
# Beacon settings
|
||||
beacon:
|
||||
|
||||
# File or command (prefix: "|") to use for storing beacons
|
||||
#store: ""
|
||||
|
||||
# File or command (prefix: "|") to use for loading beacons
|
||||
#load: ""
|
||||
|
||||
# How often to load and store beacons (in seconds)
|
||||
interval: 3600
|
||||
|
||||
# Password to encrypt beacon data with
|
||||
#password: ""
|
||||
|
||||
|
||||
# Statsd settings
|
||||
#statsd:
|
||||
|
||||
# Statsd server name:port
|
||||
#server: ""
|
||||
|
||||
# Prefix to use for stats keys
|
||||
#prefix: ""
|
||||
# Copy this template and save it to a file named /etc/vpncloud/MYNET.net (replace MYNET with your network name)
|
||||
#
|
||||
# On systems using systemd (most common):
|
||||
# start/stop the network: service vpncloud@MYNET start/stop
|
||||
# enable/disable automatic startup: systemctl enable/disable vpncloud@MYNET
|
||||
#
|
||||
# On older systems (using sysv init):
|
||||
# Add the network name to /etc/default/vpncloud
|
||||
# start/stop all VpnCloud networks: /etc/init.d/vpncloud start/stop
|
|
@ -0,0 +1,22 @@
|
|||
[Unit]
|
||||
Description=VpnCloud websocket proxy
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
Documentation=man:vpncloud(1)
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/usr/bin/vpncloud ws-proxy -l 3210
|
||||
RestartSec=5s
|
||||
Restart=on-failure
|
||||
TasksMax=10
|
||||
MemoryMax=50M
|
||||
PrivateTmp=yes
|
||||
ProtectHome=yes
|
||||
ProtectSystem=strict
|
||||
ReadWritePaths=/var/log /run
|
||||
CapabilityBoundingSet=CAP_NET_BIND_SERVICE CAP_SYS_CHROOT
|
||||
DeviceAllow=/dev/null rw
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
|
@ -1,860 +0,0 @@
|
|||
'\" t
|
||||
.\" Title: vpncloud
|
||||
.\" Author: [see the "AUTHORS" section]
|
||||
.\" Generator: Asciidoctor 1.5.5
|
||||
.\" Date: 2020-06-03
|
||||
.\" Manual: \ \&
|
||||
.\" Source: \ \&
|
||||
.\" Language: English
|
||||
.\"
|
||||
.TH "VPNCLOUD" "1" "2020-06-03" "\ \&" "\ \&"
|
||||
.ie \n(.g .ds Aq \(aq
|
||||
.el .ds Aq '
|
||||
.ss \n[.ss] 0
|
||||
.nh
|
||||
.ad l
|
||||
.de URL
|
||||
\\$2 \(laURL: \\$1 \(ra\\$3
|
||||
..
|
||||
.if \n[.g] .mso www.tmac
|
||||
.LINKSTYLE blue R < >
|
||||
.SH "NAME"
|
||||
vpncloud \- Peer\-to\-peer VPN
|
||||
.SH "SYNOPSIS"
|
||||
.sp
|
||||
\fBvpncloud [options] [\-\-config <file>] [\-t <type>] [\-d <name>] [\-l <addr>] [\-c <addr>...]\fP
|
||||
.SH "OPTIONS"
|
||||
.sp
|
||||
\fB\-\-config <file>\fP
|
||||
.RS 4
|
||||
Read configuration options from the specified file. Please see the section
|
||||
\fBCONFIG FILES\fP for documentation on the file format.
|
||||
If the same option is defined in the config file and as a parameter, the
|
||||
parameter overrides the config file.
|
||||
.RE
|
||||
.sp
|
||||
\fB\-t <type>\fP, \fB\-\-type <type>\fP
|
||||
.RS 4
|
||||
Set the type of network. There are two options: \fBtap\fP devices process
|
||||
Ethernet frames \fBtun\fP devices process IP packets. [default: \fBtap\fP]
|
||||
.RE
|
||||
.sp
|
||||
\fB\-d <name>\fP, \fB\-\-device <name>\fP
|
||||
.RS 4
|
||||
Name of the virtual device. Any \fB%d\fP will be filled with a free number.
|
||||
[default: \fBvpncloud%d\fP]
|
||||
.RE
|
||||
.sp
|
||||
\fB\-\-device\-path <path>\fP
|
||||
.RS 4
|
||||
The path of the base device inode, e.g. /dev/net/run.
|
||||
.RE
|
||||
.sp
|
||||
\fB\-m <mode>\fP, \fB\-\-mode <mode>\fP
|
||||
.RS 4
|
||||
The mode of the VPN. The VPN can like a router, a switch or a hub. A \fBhub\fP
|
||||
will send all data always to all peers. A \fBswitch\fP will learn addresses
|
||||
from incoming data and only send data to all peers when the address is
|
||||
unknown. A \fBrouter\fP will send data according to known subnets of the
|
||||
peers and ignore them otherwise. The \fBnormal\fP mode is switch for tap
|
||||
devices and router for tun devices. [default: \fBnormal\fP]
|
||||
.RE
|
||||
.sp
|
||||
\fB\-l <addr>\fP, \fB\-\-listen <addr>\fP
|
||||
.RS 4
|
||||
The address on which to listen for data. This can be simply a port number
|
||||
or a full address in form IP:PORT. If the IP is specified as \(aq\(rs*\(aq or only
|
||||
a port number is given, then the socket will listen on all IPs (v4 and v6),
|
||||
otherwise the socket will only listen on the given IP. [default: \fB3210\fP]
|
||||
.RE
|
||||
.sp
|
||||
\fB\-c <addr>\fP, \fB\-\-connect <addr>\fP
|
||||
.RS 4
|
||||
Address of a peer to connect to. The address should be in the form
|
||||
\fBaddr:port\fP. If the node is not started, the connection will be retried
|
||||
periodically. This parameter can be repeated to connect to multiple peers.
|
||||
.RE
|
||||
.sp
|
||||
\fB\-s <subnet>\fP, \fB\-\-subnet <subnet>\fP:
|
||||
The local subnets to use. This parameter should be in the form
|
||||
\fBaddress/prefixlen\fP where address is an IPv4 address, an IPv6 address, or a
|
||||
MAC address. The prefix length is the number of significant front bits that
|
||||
distinguish the subnet from other subnets. Example: \fB10.1.1.0/24\fP.
|
||||
.sp
|
||||
\fB\-\-shared\-key <key>\fP
|
||||
.RS 4
|
||||
An optional shared key to encrypt the VPN data. If this option is not set,
|
||||
the traffic will be sent unencrypted.
|
||||
.RE
|
||||
.sp
|
||||
\fB\-\-crypto <method>\fP
|
||||
.RS 4
|
||||
The encryption method to use ("aes256", or "chacha20"). Most current CPUs
|
||||
have special support for AES256 so this should be faster. For older
|
||||
computers lacking this support, only CHACHA20 is supported.
|
||||
[default: \fBchacha20\fP]
|
||||
.RE
|
||||
.sp
|
||||
\fB\-\-magic <id>\fP
|
||||
.RS 4
|
||||
Override the 4\-byte magic header of each packet. This header identifies the
|
||||
network and helps to distinguish it from other networks and other
|
||||
applications. The id can either be a 4 byte / 8 character hexadecimal
|
||||
string or an arbitrary string prefixed with "hash:" which will then be
|
||||
hashed into 4 bytes.
|
||||
.RE
|
||||
.sp
|
||||
\fB\-\-peer\-timeout <secs>\fP
|
||||
.RS 4
|
||||
Peer timeout in seconds. The peers will exchange information periodically
|
||||
and drop peers that are silent for this period of time. [default: \fB600\fP]
|
||||
.RE
|
||||
.sp
|
||||
\fB\-\-keepalive <secs>\fP
|
||||
.RS 4
|
||||
Interval of peer exchange messages in seconds. The peers will exchange
|
||||
information periodically to keep connections alive. This setting overrides
|
||||
how often this will happen. [default: \fBpeer\-timeout/2\-60\fP]
|
||||
.RE
|
||||
.sp
|
||||
\fB\-\-dst\-timeout <secs>\fP
|
||||
.RS 4
|
||||
Switch table entry timeout in seconds. This parameter is only used in switch
|
||||
mode. Addresses that have not been seen for the given period of time will
|
||||
be forgotten. [default: \fB300\fP]
|
||||
.RE
|
||||
.sp
|
||||
\fB\-\-beacon\-store <path|command>\fP
|
||||
.RS 4
|
||||
Periodically store beacons containing the address of this node in the given
|
||||
file or via the given command. If the parameter value starts with a pipe
|
||||
character (\fB|\fP), the rest of the value is interpreted as a shell command.
|
||||
Otherwise the value is interpreted as a file to write the beacon to.
|
||||
If this parameter is not given, beacon storage is disabled.
|
||||
Please see the section \fBBEACONS\fP for more information.
|
||||
.RE
|
||||
.sp
|
||||
\fB\-\-beacon\-load <path|command>\fP
|
||||
.RS 4
|
||||
Periodically load beacons containing the addresses of other nodes from the
|
||||
given file or via the given command. If the parameter value starts with a
|
||||
pipe character (\fB|\fP), the rest of the value is interpreted as a shell
|
||||
command. Otherwise the value is interpreted as a file to read the beacon
|
||||
from.
|
||||
If this parameter is not given, beacon loading is disabled.
|
||||
Please see the section \fBBEACONS\fP for more information.
|
||||
.RE
|
||||
.sp
|
||||
\fB\-\-beacon\-interval <secs>\fP
|
||||
.RS 4
|
||||
Beacon storage/loading interval in seconds. If configured to do so via
|
||||
\fB\-\-beacon\-store\fP and \fB\-\-beacon\-load\fP, the node will periodically store its
|
||||
beacon and load beacons of other nodes. This parameter defines the interval
|
||||
in seconds. [default: \fB3600\fP]
|
||||
.RE
|
||||
.sp
|
||||
\fB\-\-ifup <command>\fP
|
||||
.RS 4
|
||||
A command to setup the network interface. The command will be run (as
|
||||
parameter to \fBsh \-c\fP) when the device has been created to configure it.
|
||||
The name of the allocated device will be available via the environment
|
||||
variable \fBIFNAME\fP.
|
||||
Please note that this command is executed with the full permissions of the
|
||||
caller.
|
||||
.RE
|
||||
.sp
|
||||
\fB\-\-ifdown <command>\fP
|
||||
.RS 4
|
||||
A command to bring down the network interface. The command will be run (as
|
||||
parameter to \fBsh \-c\fP) to remove any configuration from the device.
|
||||
The name of the allocated device will be available via the environment
|
||||
variable \fBIFNAME\fP.
|
||||
Please note that this command is executed with the (limited) permissions of
|
||||
the user and group given as \fB\-\-user\fP and \fB\-\-group\fP.
|
||||
.RE
|
||||
.sp
|
||||
\fB\-\-pid\-file <file>\fP
|
||||
.RS 4
|
||||
Store the process id in this file when running in the background. If set,
|
||||
the given file will be created containing the process id of the new
|
||||
background process. This option is only used when running in background.
|
||||
.RE
|
||||
.sp
|
||||
\fB\-\-user <user>\fP, \fB\-\-group <group>\fP
|
||||
.RS 4
|
||||
Change the user and/or group of the process once all the setup has been
|
||||
done.
|
||||
.RE
|
||||
.sp
|
||||
\fB\-\-log\-file <file>\fP
|
||||
.RS 4
|
||||
If set, print logs also to the given file. The file will be created and
|
||||
truncated if is exists.
|
||||
.RE
|
||||
.sp
|
||||
\fB\-\-stats\-file <file>\fP
|
||||
.RS 4
|
||||
If set, periodically write statistics on peers and current traffic to the
|
||||
given file. The file will be periodically overwritten with new data.
|
||||
.RE
|
||||
.sp
|
||||
\fB\-\-daemon\fP
|
||||
.RS 4
|
||||
Spawn a background process instead of running the process in the foreground.
|
||||
If this flag is set, the process will first carry out all the
|
||||
initialization, then drop permissions if \fB\-\-user\fP or \fB\-\-group\fP is used and
|
||||
then spawn a background process and write its process id to a file if
|
||||
\fB\-\-pid\-file\fP is set. Then, the main process will exit and the background
|
||||
process continues to provide the VPN. At the time, when the main process
|
||||
exits, the interface exists and is properly configured to be used.
|
||||
.RE
|
||||
.sp
|
||||
\fB\-\-no\-port\-forwarding\fP
|
||||
.RS 4
|
||||
Disable automatic port forward. If this option is not set, VpnCloud tries to
|
||||
detect a NAT router and automatically add a port forwarding to it.
|
||||
.RE
|
||||
.sp
|
||||
\fB\-v\fP, \fB\-\-verbose\fP
|
||||
.RS 4
|
||||
Print debug information, including information for data being received and
|
||||
sent.
|
||||
.RE
|
||||
.sp
|
||||
\fB\-q\fP, \fB\-\-quiet\fP
|
||||
.RS 4
|
||||
Only print errors and warnings.
|
||||
.RE
|
||||
.sp
|
||||
\fB\-h\fP, \fB\-\-help\fP
|
||||
.RS 4
|
||||
Display the help.
|
||||
.RE
|
||||
.SH "DESCRIPTION"
|
||||
.sp
|
||||
\fBVpnCloud\fP is a simple VPN over UDP. It creates a virtual network interface on
|
||||
the host and forwards all received data via UDP to the destination. It can work
|
||||
in 3 different modes:
|
||||
.sp
|
||||
\fBSwitch mode\fP
|
||||
.RS 4
|
||||
In this mode, the VPN will dynamically learn addresses
|
||||
as they are used as source addresses and use them to forward data to its
|
||||
destination. Addresses that have not been seen for some time
|
||||
(option \fBswitch_timeout\fP) will be forgotten. Data for unknown addresses will be
|
||||
broadcast to all peers. This mode is the default mode for TAP devices that
|
||||
process Ethernet frames but it can also be used with TUN devices and IP
|
||||
packets.
|
||||
.RE
|
||||
.sp
|
||||
\fBHub mode\fP
|
||||
.RS 4
|
||||
In this mode, all data will always be broadcast to all peers.
|
||||
This mode uses lots of bandwidth and should only be used in special cases.
|
||||
.RE
|
||||
.sp
|
||||
\fBRouter mode\fP
|
||||
.RS 4
|
||||
In this mode, data will be forwarded based on preconfigured
|
||||
address ranges ("subnets"). Data for unknown nodes will be silently ignored.
|
||||
This mode is the default mode for TUN devices that work with IP packets but
|
||||
it can also be used with TAP devices and Ethernet frames.
|
||||
.RE
|
||||
.sp
|
||||
All connected VpnCloud nodes will form a peer\-to\-peer network and cross\-connect
|
||||
automatically until the network is fully connected. The nodes will periodically
|
||||
exchange information with the other nodes to signal that they are still active
|
||||
and to allow the automatic cross\-connect behavior. There are some important
|
||||
things to note:
|
||||
.sp
|
||||
.RS 4
|
||||
.ie n \{\
|
||||
\h'-04' 1.\h'+01'\c
|
||||
.\}
|
||||
.el \{\
|
||||
.sp -1
|
||||
.IP " 1." 4.2
|
||||
.\}
|
||||
To avoid that different networks that reuse each others addresses merge due
|
||||
to the cross\-connect behavior, the \fBmagic\fP option can be used and set
|
||||
to any unique string to identify the network. The \fBmagic\fP must be the
|
||||
same on all nodes of the same VPN network.
|
||||
.RE
|
||||
.sp
|
||||
.RS 4
|
||||
.ie n \{\
|
||||
\h'-04' 2.\h'+01'\c
|
||||
.\}
|
||||
.el \{\
|
||||
.sp -1
|
||||
.IP " 2." 4.2
|
||||
.\}
|
||||
The cross\-connect behavior can be able to connect nodes that are behind
|
||||
firewalls or NATs as it can function as hole\-punching.
|
||||
.RE
|
||||
.sp
|
||||
.RS 4
|
||||
.ie n \{\
|
||||
\h'-04' 3.\h'+01'\c
|
||||
.\}
|
||||
.el \{\
|
||||
.sp -1
|
||||
.IP " 3." 4.2
|
||||
.\}
|
||||
The management traffic will increase with the peer number quadratically.
|
||||
It should still be reasonably small for high node numbers (below 10 KiB/s
|
||||
for 10.000 nodes). A longer \fBpeer_timeout\fP can be used to reduce the traffic
|
||||
further. For high node numbers, router mode should be used as it never
|
||||
broadcasts data.
|
||||
.RE
|
||||
.sp
|
||||
VpnCloud does not implement any loop\-avoidance. Since data received on the UDP
|
||||
socket will only be sent to the local network interface and vice versa, VpnCloud
|
||||
cannot produce loops on its own. On the TAP device, however STP data can be
|
||||
transported to avoid loops caused by other network components.
|
||||
.sp
|
||||
For TAP devices, IEEE 802.1q frames (VLAN tagged) are detected and forwarded
|
||||
based on separate MAC tables. Any nested tags (Q\-in\-Q) will be ignored.
|
||||
.SH "EXAMPLES"
|
||||
.SS "Switched TAP scenario"
|
||||
.sp
|
||||
In the example scenario, a simple layer 2 network tunnel is established. Most
|
||||
likely those commands need to be run as \fBroot\fP using \fBsudo\fP.
|
||||
.sp
|
||||
First, VpnCloud need to be started on both nodes (the address after \fB\-c\fP is the
|
||||
address of the remote node and the the \fBX\fP in the interface address must be
|
||||
unique among all nodes, e.g. 0, 1, 2, ...):
|
||||
.sp
|
||||
.if n \{\
|
||||
.RS 4
|
||||
.\}
|
||||
.nf
|
||||
vpncloud \-c REMOTE_HOST:PORT \-\-ifup \(aqifconfig $IFNAME 10.0.0.X/24 mtu 1400 up\(aq
|
||||
.fi
|
||||
.if n \{\
|
||||
.RE
|
||||
.\}
|
||||
.sp
|
||||
Afterwards, the interface can be used to communicate.
|
||||
.SS "Routed TUN example"
|
||||
.sp
|
||||
In this example, 2 nodes and their subnets should communicate using IP.
|
||||
First, VpnCloud need to be started on both nodes:
|
||||
.sp
|
||||
.if n \{\
|
||||
.RS 4
|
||||
.\}
|
||||
.nf
|
||||
vpncloud \-t tun \-c REMOTE_HOST:PORT \-\-subnet 10.0.X.0/24 \-\-ifup \(aqifconfig $IFNAME 10.0.X.1/16 mtu 1400 up\(aq
|
||||
.fi
|
||||
.if n \{\
|
||||
.RE
|
||||
.\}
|
||||
.sp
|
||||
It is important to configure the interface in a way that all addresses on the
|
||||
VPN can be reached directly. E.g. if subnets 10.0.1.0/24, 10.0.2.0/24 and so on
|
||||
are used, the interface needs to be configured as 10.0.1.1/16.
|
||||
For TUN devices, this means that the prefix length of the subnets
|
||||
(/24 in this example) must be different than the prefix length that the
|
||||
interface is configured with (/16 in this example).
|
||||
.SS "Important notes"
|
||||
.sp
|
||||
.RS 4
|
||||
.ie n \{\
|
||||
\h'-04' 1.\h'+01'\c
|
||||
.\}
|
||||
.el \{\
|
||||
.sp -1
|
||||
.IP " 1." 4.2
|
||||
.\}
|
||||
VpnCloud can be used to connect two separate networks. TAP networks can be
|
||||
bridged using \fBbrctl\fP and TUN networks must be routed. It is very important
|
||||
to be careful when setting up such a scenario in order to avoid network loops,
|
||||
security issues, DHCP issues and many more problems.
|
||||
.RE
|
||||
.sp
|
||||
.RS 4
|
||||
.ie n \{\
|
||||
\h'-04' 2.\h'+01'\c
|
||||
.\}
|
||||
.el \{\
|
||||
.sp -1
|
||||
.IP " 2." 4.2
|
||||
.\}
|
||||
TAP devices will forward DHCP data. If done intentionally, this can be used
|
||||
to assign unique addresses to all participants. If this happens accidentally,
|
||||
it can conflict with DHCP servers of the local network and can have severe
|
||||
side effects.
|
||||
.RE
|
||||
.sp
|
||||
.RS 4
|
||||
.ie n \{\
|
||||
\h'-04' 3.\h'+01'\c
|
||||
.\}
|
||||
.el \{\
|
||||
.sp -1
|
||||
.IP " 3." 4.2
|
||||
.\}
|
||||
VpnCloud is not designed for high security use cases. Although the used crypto
|
||||
primitives are expected to be very secure, their application has not been
|
||||
reviewed.
|
||||
The shared key is hashed using \fIScryptSalsa208Sha256\fP to derive a key,
|
||||
which is used to encrypt the payload of messages using \fIChaCha20Poly1305\fP or
|
||||
\fIAES256\-GCM\fP. The encryption includes an authentication that also protects the
|
||||
header.
|
||||
This method does only protect against attacks on single messages but not
|
||||
against attacks that manipulate the message series itself (i.e. suppress
|
||||
messages, reorder them, or duplicate them).
|
||||
.RE
|
||||
.SH "CONFIG FILES"
|
||||
.sp
|
||||
The config file is a YAML file that contains configuration values. All entries
|
||||
are optional and override the defaults. Please see the section \fBOPTIONS\fP for
|
||||
detailed descriptions of the options.
|
||||
.sp
|
||||
\fBdevice_type\fP
|
||||
.RS 4
|
||||
Set the type of network. Same as \fB\-\-type\fP
|
||||
.RE
|
||||
.sp
|
||||
\fBdevice_name\fP
|
||||
.RS 4
|
||||
Name of the virtual device. Same as \fB\-\-device\fP
|
||||
.RE
|
||||
.sp
|
||||
\fBdevice_path\fP
|
||||
.RS 4
|
||||
Set the path of the base device. Same as \fB\-\-device\-path\fP
|
||||
.RE
|
||||
.sp
|
||||
\fBifup\fP
|
||||
.RS 4
|
||||
A command to setup the network interface. Same as \fB\-\-ifup\fP
|
||||
.RE
|
||||
.sp
|
||||
\fBifdown\fP
|
||||
.RS 4
|
||||
A command to bring down the network interface. Same as \fB\-\-ifdown\fP
|
||||
.RE
|
||||
.sp
|
||||
\fBcrypto\fP
|
||||
.RS 4
|
||||
The encryption method to use. Same as \fB\-\-crypto\fP
|
||||
.RE
|
||||
.sp
|
||||
\fBshared_key\fP
|
||||
.RS 4
|
||||
The shared key to encrypt all traffic. Same as \fB\-\-shared\-key\fP
|
||||
.RE
|
||||
.sp
|
||||
\fBmagic\fP
|
||||
.RS 4
|
||||
Override the 4\-byte magic header of each packet. Same as \fB\-\-magic\fP
|
||||
.RE
|
||||
.sp
|
||||
\fBport\fP
|
||||
.RS 4
|
||||
A port number to listen on. This option is DEPRECATED.
|
||||
.RE
|
||||
.sp
|
||||
\fBlisten\fP
|
||||
.RS 4
|
||||
The address on which to listen for data. Same as \fB\-\-listen\fP
|
||||
.RE
|
||||
.sp
|
||||
\fBpeers\fP
|
||||
.RS 4
|
||||
A list of addresses to connect to. See \fB\-\-connect\fP
|
||||
.RE
|
||||
.sp
|
||||
\fBpeer_timeout\fP
|
||||
.RS 4
|
||||
Peer timeout in seconds. Same as\fB\-\-peer\-timeout\fP
|
||||
.RE
|
||||
.sp
|
||||
\fBbeacon_store\fP
|
||||
.RS 4
|
||||
Path or command to store beacons. Same as \fB\-\-beacon\-store\fP
|
||||
.RE
|
||||
.sp
|
||||
\fBbeacon_load\fP
|
||||
.RS 4
|
||||
Path or command to load beacons. Same as \fB\-\-beacon\-load\fP
|
||||
.RE
|
||||
.sp
|
||||
\fBbeacon_interval\fP
|
||||
.RS 4
|
||||
Interval for loading and storing beacons in seconds. Same as \fB\-\-beacon\-interval\fP
|
||||
.RE
|
||||
.sp
|
||||
\fBmode\fP
|
||||
.RS 4
|
||||
The mode of the VPN. Same as \fB\-\-mode\fP
|
||||
.RE
|
||||
.sp
|
||||
\fBswitch_timeout\fP
|
||||
.RS 4
|
||||
Switch table entry timeout in seconds. Same as \fB\-\-dst\-timeout\fP
|
||||
.RE
|
||||
.sp
|
||||
\fBsubnets\fP
|
||||
.RS 4
|
||||
A list of local subnets to use. See \fB\-\-subnet\fP
|
||||
.RE
|
||||
.sp
|
||||
\fBport_forwarding\fP
|
||||
.RS 4
|
||||
Whether to activate port forwardig. See \fB\-\-no\-port\-forwarding\fP
|
||||
.RE
|
||||
.sp
|
||||
\fBuser\fP
|
||||
.RS 4
|
||||
The name of a user to run the background process under. See \fB\-\-user\fP
|
||||
.RE
|
||||
.sp
|
||||
\fBgroup\fP
|
||||
.RS 4
|
||||
The name of a group to run the background process under. See \fB\-\-group\fP
|
||||
.RE
|
||||
.sp
|
||||
\fBpid_file\fP
|
||||
.RS 4
|
||||
The path of the pid file to create. See \fB\-\-pid\-file\fP
|
||||
.RE
|
||||
.sp
|
||||
\fBstats_file\fP
|
||||
.RS 4
|
||||
The path of the statistics file. See \fB\-\-stats\-file\fP
|
||||
.RE
|
||||
.SS "Example"
|
||||
.sp
|
||||
.if n \{\
|
||||
.RS 4
|
||||
.\}
|
||||
.nf
|
||||
device_type: tun
|
||||
device_name: vpncloud%d
|
||||
ifup: ifconfig $IFNAME 10.0.1.1/16 mtu 1400 up
|
||||
crypto: aes256
|
||||
shared_key: mysecret
|
||||
listen: 3210
|
||||
peers:
|
||||
\- remote.machine.foo:3210
|
||||
\- remote.machine.bar:3210
|
||||
peer_timeout: 600
|
||||
mode: normal
|
||||
subnets:
|
||||
\- 10.0.1.0/24
|
||||
port_forwarding: true
|
||||
user: nobody
|
||||
group: nogroup
|
||||
pid_file: /run/vpncloud.pid
|
||||
.fi
|
||||
.if n \{\
|
||||
.RE
|
||||
.\}
|
||||
.SH "BEACONS"
|
||||
.sp
|
||||
Beacons are short character sequences that contain a timestamp and a list of
|
||||
addresses. They can be published and retrieved by other nodes to find peers
|
||||
without the need for static addresses.
|
||||
.sp
|
||||
The beacons are short (less than 100 characters), encrypted and encoded with
|
||||
printable characters to allow publishing them in various places on the
|
||||
internet, e.g.:
|
||||
.sp
|
||||
.RS 4
|
||||
.ie n \{\
|
||||
\h'-04'\(bu\h'+03'\c
|
||||
.\}
|
||||
.el \{\
|
||||
.sp -1
|
||||
.IP \(bu 2.3
|
||||
.\}
|
||||
On shared drives or synchronized folders (e.g. on Dropbox)
|
||||
.RE
|
||||
.sp
|
||||
.RS 4
|
||||
.ie n \{\
|
||||
\h'-04'\(bu\h'+03'\c
|
||||
.\}
|
||||
.el \{\
|
||||
.sp -1
|
||||
.IP \(bu 2.3
|
||||
.\}
|
||||
Via a dedicated database
|
||||
.RE
|
||||
.sp
|
||||
.RS 4
|
||||
.ie n \{\
|
||||
\h'-04'\(bu\h'+03'\c
|
||||
.\}
|
||||
.el \{\
|
||||
.sp -1
|
||||
.IP \(bu 2.3
|
||||
.\}
|
||||
Via a general purpose message board of message service (e.g. Twitter)
|
||||
.RE
|
||||
.sp
|
||||
The beacons are very robust. They only consist of alphanumeric characters
|
||||
and can be interleaved with non\-alphanumeric characters (e.g. whitespace).
|
||||
Also the beacons contain a prefix and suffix that depends on the configured
|
||||
network magic and secret key (if set) so that all nodes can find beacons in
|
||||
a long text.
|
||||
.sp
|
||||
When beacons are stored or loaded via a command (using the pipe character \fB|\fP),
|
||||
the command is interpreted using the configured shell \fBsh\fP. This command has
|
||||
access to the following environment variables:
|
||||
.sp
|
||||
\fB$begin\fP
|
||||
.RS 4
|
||||
The prefix of the beacon.
|
||||
.RE
|
||||
.sp
|
||||
\fB$end\fP
|
||||
.RS 4
|
||||
The suffix of the beacon.
|
||||
.RE
|
||||
.sp
|
||||
\fB$data\fP (only on store)
|
||||
.RS 4
|
||||
The middle part of the beacon. Do not use this
|
||||
without prefix and suffix!
|
||||
.RE
|
||||
.sp
|
||||
\fB$beacon\fP (only on store)
|
||||
.RS 4
|
||||
The full beacon consisting of prefix, data and
|
||||
suffix.
|
||||
The commands are called in separate threads, so even longer running commands
|
||||
will not block the node.
|
||||
.RE
|
||||
.SH "NETWORK PROTOCOL"
|
||||
.sp
|
||||
The protocol of VpnCloud is kept as simple as possible to allow other
|
||||
implementations and to maximize the performance.
|
||||
.sp
|
||||
Every packet sent over UDP contains the following header (in order):
|
||||
.sp
|
||||
4 bytes \fBmagic\fP
|
||||
.RS 4
|
||||
This field is used to identify the packet and to sort out packets that do
|
||||
not belong. The default is \fB[0x76, 0x70, 0x6e, 0x01]\fP ("vpn\(rsx01").
|
||||
This field can be used to identify VpnCloud packets and might be set to
|
||||
something different to hide the protocol.
|
||||
.RE
|
||||
.sp
|
||||
1 byte \fBcrypto method\fP
|
||||
.RS 4
|
||||
This field specifies the method that must be used to decrypt the rest of the
|
||||
data. The currently supported methods are:
|
||||
.sp
|
||||
.RS 4
|
||||
.ie n \{\
|
||||
\h'-04'\(bu\h'+03'\c
|
||||
.\}
|
||||
.el \{\
|
||||
.sp -1
|
||||
.IP \(bu 2.3
|
||||
.\}
|
||||
Method \fB0\fP, \fBNo encryption\fP: Rest of the data can be read without
|
||||
decrypting it.
|
||||
.RE
|
||||
.sp
|
||||
.RS 4
|
||||
.ie n \{\
|
||||
\h'-04'\(bu\h'+03'\c
|
||||
.\}
|
||||
.el \{\
|
||||
.sp -1
|
||||
.IP \(bu 2.3
|
||||
.\}
|
||||
Method \fB1\fP, \fBChaCha20\fP: The header is followed by a 12 byte
|
||||
\fInonce\fP. The rest of the data is encrypted with the
|
||||
\fBlibsodium::crypto_aead_chacha20poly1305_ietf\fP method, using the 8 byte
|
||||
header as additional data.
|
||||
.RE
|
||||
.sp
|
||||
.RS 4
|
||||
.ie n \{\
|
||||
\h'-04'\(bu\h'+03'\c
|
||||
.\}
|
||||
.el \{\
|
||||
.sp -1
|
||||
.IP \(bu 2.3
|
||||
.\}
|
||||
Method \fB2\fP, \fBAES256\fP: The header is followed by a 12 byte \fInonce\fP.
|
||||
The rest of the data is encrypted with the
|
||||
\fBlibsodium::crypto_aead_aes256gcm\fP method, using the 8 byte header
|
||||
as additional data.
|
||||
.RE
|
||||
.RE
|
||||
.sp
|
||||
2 \fBreserved bytes\fP
|
||||
.RS 4
|
||||
that are currently unused and set to 0
|
||||
.RE
|
||||
.sp
|
||||
1 byte for the \fBmessage type\fP
|
||||
.RS 4
|
||||
This byte specifies the type of message that follows. Currently the
|
||||
following message types are supported:
|
||||
.sp
|
||||
.RS 4
|
||||
.ie n \{\
|
||||
\h'-04'\(bu\h'+03'\c
|
||||
.\}
|
||||
.el \{\
|
||||
.sp -1
|
||||
.IP \(bu 2.3
|
||||
.\}
|
||||
Type 0: Data packet
|
||||
.RE
|
||||
.sp
|
||||
.RS 4
|
||||
.ie n \{\
|
||||
\h'-04'\(bu\h'+03'\c
|
||||
.\}
|
||||
.el \{\
|
||||
.sp -1
|
||||
.IP \(bu 2.3
|
||||
.\}
|
||||
Type 1: Peer list
|
||||
.RE
|
||||
.sp
|
||||
.RS 4
|
||||
.ie n \{\
|
||||
\h'-04'\(bu\h'+03'\c
|
||||
.\}
|
||||
.el \{\
|
||||
.sp -1
|
||||
.IP \(bu 2.3
|
||||
.\}
|
||||
Type 2: Initial message
|
||||
.RE
|
||||
.sp
|
||||
.RS 4
|
||||
.ie n \{\
|
||||
\h'-04'\(bu\h'+03'\c
|
||||
.\}
|
||||
.el \{\
|
||||
.sp -1
|
||||
.IP \(bu 2.3
|
||||
.\}
|
||||
Type 3: Closing message
|
||||
.RE
|
||||
.RE
|
||||
.sp
|
||||
After this 8 byte header, the rest of the message follows. It is encrypted using
|
||||
the method specified in the header.
|
||||
.sp
|
||||
In the decrypted data, the message as specified in the \fBmessage type\fP field
|
||||
will follow:
|
||||
.sp
|
||||
\fBData packet\fP (message type 0)
|
||||
.RS 4
|
||||
This packet contains payload. The format of the data depends on the device
|
||||
type. For TUN devices, this data contains an IP packet. For TAP devices it
|
||||
contains an Ethernet frame. The data starts right after the header and ends
|
||||
at the end of the packet.
|
||||
If it is an Ethernet frame, it will start with the destination MAC and end
|
||||
with the payload. It does not contain the preamble, SFD, padding, and CRC
|
||||
fields.
|
||||
.RE
|
||||
.sp
|
||||
\fBPeer list\fP (message type 1)
|
||||
.RS 4
|
||||
This packet contains the peer list of the sender. The first byte after the
|
||||
switch byte contains the number of IPv4 addresses that follow.
|
||||
After that, the specified number of addresses follow, where each address
|
||||
is encoded in 6 bytes. The first 4 bytes are the IPv4 address and the later
|
||||
2 bytes are port number (both in network byte order).
|
||||
After those addresses, the next byte contains the number of IPv6 addresses
|
||||
that follow. After that, the specified number of addresses follow, where
|
||||
each address is encoded in 18 bytes. The first 16 bytes are the IPv6 address
|
||||
and the later 2 bytes are port number (both in network byte order).
|
||||
.RE
|
||||
.sp
|
||||
\fBInitial message\fP (message type 2)
|
||||
.RS 4
|
||||
This packet contains the following information:
|
||||
.sp
|
||||
.RS 4
|
||||
.ie n \{\
|
||||
\h'-04'\(bu\h'+03'\c
|
||||
.\}
|
||||
.el \{\
|
||||
.sp -1
|
||||
.IP \(bu 2.3
|
||||
.\}
|
||||
The stage of the initialization process
|
||||
.RE
|
||||
.sp
|
||||
.RS 4
|
||||
.ie n \{\
|
||||
\h'-04'\(bu\h'+03'\c
|
||||
.\}
|
||||
.el \{\
|
||||
.sp -1
|
||||
.IP \(bu 2.3
|
||||
.\}
|
||||
A random node id to distinguish different nodes
|
||||
.RE
|
||||
.sp
|
||||
.RS 4
|
||||
.ie n \{\
|
||||
\h'-04'\(bu\h'+03'\c
|
||||
.\}
|
||||
.el \{\
|
||||
.sp -1
|
||||
.IP \(bu 2.3
|
||||
.\}
|
||||
All the local subnets claimed by the nodes
|
||||
.RE
|
||||
.sp
|
||||
Its first byte marks the stage of the initial handshake process.
|
||||
The next 16 bytes contain the unique node id. After that,
|
||||
the list of local subnets follows.
|
||||
The subnet list is encoded in the following way: Its first byte of data
|
||||
contains the number of encoded subnets that follow. After that, the given
|
||||
number of encoded subnets follow.
|
||||
For each subnet, the first byte is the length of bytes in the base address
|
||||
and is followed by the given number of base address bytes and one additional
|
||||
byte that is the prefix length of the subnet.
|
||||
The addresses for the subnet will be encoded like they are encoded in their
|
||||
native protocol (4 bytes for IPv4, 16 bytes for IPv6, and 6 bytes for a MAC
|
||||
address) with the exception of MAC addresses in a VLan which will be encoded
|
||||
in 8 bytes where the first 2 bytes are the VLan number in network byte order
|
||||
and the later 6 bytes are the MAC address.
|
||||
.RE
|
||||
.sp
|
||||
\fBClosing message\fP (message type 3)
|
||||
.RS 4
|
||||
This packet does not contain any more data.
|
||||
.RE
|
||||
.sp
|
||||
Nodes are expected to send an \fBinitial message\fP with stage 0 whenever they
|
||||
connect to a node they were not connected to before. As a reply to this message,
|
||||
another initial should be sent with stage 1. Also a \fBpeer list\fP message should
|
||||
be sent as a reply.
|
||||
.sp
|
||||
When connected, nodes should periodically send their \fBpeer list\fP to all
|
||||
of their peers to spread this information and to avoid peer timeouts.
|
||||
To avoid the cubic growth of management traffic, nodes should at a certain
|
||||
network size start sending partial peer lists instead of the full list. A
|
||||
reasonable number would be about 20 peers. The subsets should be selected
|
||||
randomly.
|
||||
.sp
|
||||
Nodes should remove peers from their peer list after a certain period of
|
||||
inactivity or when receiving a \fBclosing message\fP. Before shutting down, nodes
|
||||
should send the closing message to all of their peers in order to avoid
|
||||
receiving further data until the timeout is reached.
|
||||
.sp
|
||||
Nodes should only add nodes to their peer list after receiving an initial
|
||||
message from them instead of adding them right from the peer list of another
|
||||
peer. This is necessary to avoid the case of a large network keeping dead nodes
|
||||
alive.
|
||||
.SH "COPYRIGHT"
|
||||
.sp
|
||||
Copyright \(co 2015\-2020 Dennis Schwerdel
|
||||
This software is licensed under GPL\-3 or newer (see LICENSE.md)
|
|
@ -0,0 +1,77 @@
|
|||
#[macro_use]
|
||||
mod util {
|
||||
include!("../src/util.rs");
|
||||
}
|
||||
mod error {
|
||||
include!("../src/error.rs");
|
||||
}
|
||||
mod payload {
|
||||
include!("../src/payload.rs");
|
||||
}
|
||||
mod types {
|
||||
include!("../src/types.rs");
|
||||
}
|
||||
mod table {
|
||||
include!("../src/table.rs");
|
||||
}
|
||||
mod cloud {
|
||||
include!("../src/cloud.rs");
|
||||
}
|
||||
mod config {
|
||||
include!("../src/config.rs");
|
||||
}
|
||||
mod device {
|
||||
include!("../src/device.rs");
|
||||
}
|
||||
mod net {
|
||||
include!("../src/net.rs");
|
||||
}
|
||||
mod beacon {
|
||||
include!("../src/beacon.rs");
|
||||
}
|
||||
mod messages {
|
||||
include!("../src/messages.rs");
|
||||
}
|
||||
mod port_forwarding {
|
||||
include!("../src/port_forwarding.rs");
|
||||
}
|
||||
mod traffic {
|
||||
include!("../src/traffic.rs");
|
||||
}
|
||||
mod poll {
|
||||
pub mod epoll{
|
||||
include!("../src/poll/epoll.rs");
|
||||
}
|
||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
||||
pub use self::epoll::EpollWait as WaitImpl;
|
||||
|
||||
use std::io;
|
||||
|
||||
pub enum WaitResult {
|
||||
Timeout,
|
||||
Socket,
|
||||
Device,
|
||||
Error(io::Error)
|
||||
}
|
||||
}
|
||||
mod crypto {
|
||||
pub mod core {
|
||||
include!("../src/crypto/core.rs");
|
||||
}
|
||||
pub mod init {
|
||||
include!("../src/crypto/init.rs");
|
||||
}
|
||||
pub mod rotate {
|
||||
include!("../src/crypto/rotate.rs");
|
||||
}
|
||||
pub mod common {
|
||||
include!("../src/crypto/common.rs");
|
||||
}
|
||||
pub use common::*;
|
||||
pub use self::core::{EXTRA_LEN, TAG_LEN};
|
||||
}
|
||||
mod tests {
|
||||
pub mod common {
|
||||
include!("../src/tests/common.rs");
|
||||
}
|
||||
}
|
|
@ -10,31 +10,17 @@ use ring::aead;
|
|||
use std::str::FromStr;
|
||||
use std::net::{SocketAddr, Ipv4Addr, SocketAddrV4, UdpSocket};
|
||||
|
||||
mod util {
|
||||
include!("../src/util.rs");
|
||||
}
|
||||
mod error {
|
||||
include!("../src/error.rs");
|
||||
}
|
||||
mod payload {
|
||||
include!("../src/payload.rs");
|
||||
}
|
||||
mod types {
|
||||
include!("../src/types.rs");
|
||||
}
|
||||
mod table {
|
||||
include!("../src/table.rs");
|
||||
}
|
||||
mod crypto_core {
|
||||
include!("../src/crypto/core.rs");
|
||||
}
|
||||
include!(".code.rs");
|
||||
|
||||
pub use error::Error;
|
||||
use util::{MockTimeSource, MsgBuffer};
|
||||
use types::{Address, Range};
|
||||
use table::{ClaimTable};
|
||||
use device::Type;
|
||||
use config::Config;
|
||||
use payload::{Packet, Frame, Protocol};
|
||||
use crypto_core::{create_dummy_pair, EXTRA_LEN};
|
||||
use crypto::core::{create_dummy_pair, EXTRA_LEN};
|
||||
use tests::common::{TunSimulator, TapSimulator};
|
||||
|
||||
fn udp_send(c: &mut Criterion) {
|
||||
let sock = UdpSocket::bind("127.0.0.1:0").unwrap();
|
||||
|
@ -145,5 +131,74 @@ fn crypto_aes256(c: &mut Criterion) {
|
|||
crypto_bench(c, &aead::AES_256_GCM)
|
||||
}
|
||||
|
||||
criterion_group!(benches, udp_send, decode_ipv4, decode_ipv6, decode_ethernet, decode_ethernet_with_vlan, lookup_cold, lookup_warm, crypto_chacha20, crypto_aes128, crypto_aes256);
|
||||
fn full_communication_tun_router(c: &mut Criterion) {
|
||||
log::set_max_level(log::LevelFilter::Error);
|
||||
let config1 = Config {
|
||||
device_type: Type::Tun,
|
||||
auto_claim: false,
|
||||
claims: vec!["1.1.1.1/32".to_string()],
|
||||
..Config::default()
|
||||
};
|
||||
let config2 = Config {
|
||||
device_type: Type::Tun,
|
||||
auto_claim: false,
|
||||
claims: vec!["2.2.2.2/32".to_string()],
|
||||
..Config::default()
|
||||
};
|
||||
let mut sim = TunSimulator::new();
|
||||
let node1 = sim.add_node(false, &config1);
|
||||
let node2 = sim.add_node(false, &config2);
|
||||
|
||||
sim.connect(node1, node2);
|
||||
sim.simulate_all_messages();
|
||||
assert!(sim.is_connected(node1, node2));
|
||||
assert!(sim.is_connected(node2, node1));
|
||||
|
||||
let mut payload = vec![0x40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2];
|
||||
payload.append(&mut vec![0; 1400]);
|
||||
let mut g = c.benchmark_group("full_communication");
|
||||
g.throughput(Throughput::Bytes(2*1400));
|
||||
g.bench_function("tun_router", |b| {
|
||||
b.iter(|| {
|
||||
sim.put_payload(node1, payload.clone());
|
||||
sim.simulate_all_messages();
|
||||
assert_eq!(Some(&payload), sim.pop_payload(node2).as_ref());
|
||||
});
|
||||
});
|
||||
g.finish()
|
||||
}
|
||||
|
||||
fn full_communication_tap_switch(c: &mut Criterion) {
|
||||
log::set_max_level(log::LevelFilter::Error);
|
||||
let config = Config { device_type: Type::Tap, ..Config::default() };
|
||||
let mut sim = TapSimulator::new();
|
||||
let node1 = sim.add_node(false, &config);
|
||||
let node2 = sim.add_node(false, &config);
|
||||
|
||||
sim.connect(node1, node2);
|
||||
sim.simulate_all_messages();
|
||||
assert!(sim.is_connected(node1, node2));
|
||||
assert!(sim.is_connected(node2, node1));
|
||||
|
||||
let mut payload = vec![2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5];
|
||||
payload.append(&mut vec![0; 1400]);
|
||||
let mut g = c.benchmark_group("full_communication");
|
||||
g.throughput(Throughput::Bytes(2*1400));
|
||||
g.bench_function("tap_switch", |b| {
|
||||
b.iter(|| {
|
||||
sim.put_payload(node1, payload.clone());
|
||||
sim.simulate_all_messages();
|
||||
assert_eq!(Some(&payload), sim.pop_payload(node2).as_ref());
|
||||
});
|
||||
});
|
||||
g.finish()
|
||||
}
|
||||
|
||||
criterion_group!(benches,
|
||||
udp_send,
|
||||
decode_ipv4, decode_ipv6, decode_ethernet, decode_ethernet_with_vlan,
|
||||
lookup_cold, lookup_warm,
|
||||
crypto_chacha20, crypto_aes128, crypto_aes256,
|
||||
full_communication_tun_router, full_communication_tap_switch
|
||||
);
|
||||
criterion_main!(benches);
|
|
@ -0,0 +1,155 @@
|
|||
#![allow(dead_code, unused_macros, unused_imports)]
|
||||
#[macro_use] extern crate serde;
|
||||
#[macro_use] extern crate log;
|
||||
|
||||
use iai::{black_box, main};
|
||||
|
||||
use smallvec::smallvec;
|
||||
use ring::aead;
|
||||
|
||||
use std::str::FromStr;
|
||||
use std::net::{SocketAddr, Ipv4Addr, SocketAddrV4, UdpSocket};
|
||||
|
||||
include!(".code.rs");
|
||||
|
||||
pub use error::Error;
|
||||
use util::{MockTimeSource, MsgBuffer};
|
||||
use config::Config;
|
||||
use types::{Address, Range};
|
||||
use device::Type;
|
||||
use table::{ClaimTable};
|
||||
use payload::{Packet, Frame, Protocol};
|
||||
use crypto::core::{create_dummy_pair, EXTRA_LEN};
|
||||
use tests::common::{TunSimulator, TapSimulator};
|
||||
|
||||
fn udp_send() {
|
||||
let sock = UdpSocket::bind("127.0.0.1:0").unwrap();
|
||||
let data = [0; 1400];
|
||||
let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 1);
|
||||
sock.send_to(&data, &black_box(addr)).unwrap();
|
||||
}
|
||||
|
||||
fn decode_ipv4() {
|
||||
let data = [0x40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 168, 1, 1, 192, 168, 1, 2];
|
||||
Packet::parse(&black_box(data)).unwrap();
|
||||
}
|
||||
|
||||
fn decode_ipv6() {
|
||||
let data = [
|
||||
0x60, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 6, 5,
|
||||
4, 3, 2, 1
|
||||
];
|
||||
Packet::parse(&black_box(data)).unwrap();
|
||||
}
|
||||
|
||||
fn decode_ethernet() {
|
||||
let data = [6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 8];
|
||||
Frame::parse(&black_box(data)).unwrap();
|
||||
}
|
||||
|
||||
fn decode_ethernet_with_vlan() {
|
||||
let data = [6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 0x81, 0, 4, 210, 1, 2, 3, 4, 5, 6, 7, 8];
|
||||
Frame::parse(&black_box(data)).unwrap();
|
||||
}
|
||||
|
||||
fn lookup_warm() {
|
||||
let mut table = ClaimTable::<MockTimeSource>::new(60, 60);
|
||||
let addr = Address::from_str("1.2.3.4").unwrap();
|
||||
table.cache(addr, SocketAddr::from_str("1.2.3.4:3210").unwrap());
|
||||
for _ in 0..1000 {
|
||||
table.lookup(black_box(addr));
|
||||
}
|
||||
}
|
||||
|
||||
fn lookup_cold() {
|
||||
let mut table = ClaimTable::<MockTimeSource>::new(60, 60);
|
||||
let addr = Address::from_str("1.2.3.4").unwrap();
|
||||
table.set_claims(SocketAddr::from_str("1.2.3.4:3210").unwrap(), smallvec![Range::from_str("1.2.3.4/32").unwrap()]);
|
||||
for _ in 0..1000 {
|
||||
table.clear_cache();
|
||||
table.lookup(black_box(addr));
|
||||
}
|
||||
}
|
||||
|
||||
fn crypto_bench(algo: &'static aead::Algorithm) {
|
||||
let mut buffer = MsgBuffer::new(EXTRA_LEN);
|
||||
buffer.set_length(1400);
|
||||
let (mut sender, mut receiver) = create_dummy_pair(algo);
|
||||
for _ in 0..1000 {
|
||||
sender.encrypt(black_box(&mut buffer));
|
||||
receiver.decrypt(&mut buffer).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn crypto_chacha20() {
|
||||
crypto_bench(&aead::CHACHA20_POLY1305)
|
||||
}
|
||||
|
||||
fn crypto_aes128() {
|
||||
crypto_bench(&aead::AES_128_GCM)
|
||||
}
|
||||
|
||||
fn crypto_aes256() {
|
||||
crypto_bench(&aead::AES_256_GCM)
|
||||
}
|
||||
|
||||
fn full_communication_tun_router() {
|
||||
log::set_max_level(log::LevelFilter::Error);
|
||||
let config1 = Config {
|
||||
device_type: Type::Tun,
|
||||
auto_claim: false,
|
||||
claims: vec!["1.1.1.1/32".to_string()],
|
||||
..Config::default()
|
||||
};
|
||||
let config2 = Config {
|
||||
device_type: Type::Tun,
|
||||
auto_claim: false,
|
||||
claims: vec!["2.2.2.2/32".to_string()],
|
||||
..Config::default()
|
||||
};
|
||||
let mut sim = TunSimulator::new();
|
||||
let node1 = sim.add_node(false, &config1);
|
||||
let node2 = sim.add_node(false, &config2);
|
||||
|
||||
sim.connect(node1, node2);
|
||||
sim.simulate_all_messages();
|
||||
assert!(sim.is_connected(node1, node2));
|
||||
assert!(sim.is_connected(node2, node1));
|
||||
|
||||
let mut payload = vec![0x40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2];
|
||||
payload.append(&mut vec![0; 1400]);
|
||||
for _ in 0..1000 {
|
||||
sim.put_payload(node1, payload.clone());
|
||||
sim.simulate_all_messages();
|
||||
assert_eq!(Some(&payload), black_box(sim.pop_payload(node2).as_ref()));
|
||||
}
|
||||
}
|
||||
|
||||
fn full_communication_tap_switch() {
|
||||
log::set_max_level(log::LevelFilter::Error);
|
||||
let config = Config { device_type: Type::Tap, ..Config::default() };
|
||||
let mut sim = TapSimulator::new();
|
||||
let node1 = sim.add_node(false, &config);
|
||||
let node2 = sim.add_node(false, &config);
|
||||
|
||||
sim.connect(node1, node2);
|
||||
sim.simulate_all_messages();
|
||||
assert!(sim.is_connected(node1, node2));
|
||||
assert!(sim.is_connected(node2, node1));
|
||||
|
||||
let mut payload = vec![2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5];
|
||||
payload.append(&mut vec![0; 1400]);
|
||||
for _ in 0..1000 {
|
||||
sim.put_payload(node1, payload.clone());
|
||||
sim.simulate_all_messages();
|
||||
assert_eq!(Some(&payload), black_box(sim.pop_payload(node2).as_ref()));
|
||||
}
|
||||
}
|
||||
|
||||
iai::main!(
|
||||
udp_send,
|
||||
decode_ipv4, decode_ipv6, decode_ethernet, decode_ethernet_with_vlan,
|
||||
lookup_cold, lookup_warm,
|
||||
crypto_chacha20, crypto_aes128, crypto_aes256,
|
||||
full_communication_tun_router, full_communication_tap_switch
|
||||
);
|
2
build.rs
2
build.rs
|
@ -1,5 +1,5 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2020 Dennis Schwerdel
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
use std::{env, fs, path::Path, process::Command};
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2019-2020 Dennis Schwerdel
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
use ring::digest;
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2020 Dennis Schwerdel
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
use std::{
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2020 Dennis Schwerdel
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
use super::{device::Type, types::Mode, util::Duration, util::run_cmd};
|
||||
|
@ -660,43 +660,8 @@ statsd:
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn default_config_as_default() {
|
||||
let mut default_config = Config {
|
||||
device_type: Type::Tun,
|
||||
device_name: "".to_string(),
|
||||
device_path: None,
|
||||
fix_rp_filter: false,
|
||||
ip: None,
|
||||
ifup: None,
|
||||
ifdown: None,
|
||||
crypto: CryptoConfig::default(),
|
||||
listen: "[::]:3210".to_string(),
|
||||
peers: vec![],
|
||||
peer_timeout: 0,
|
||||
keepalive: None,
|
||||
beacon_store: None,
|
||||
beacon_load: None,
|
||||
beacon_interval: 0,
|
||||
beacon_password: None,
|
||||
mode: Mode::Hub,
|
||||
switch_timeout: 0,
|
||||
claims: vec![],
|
||||
auto_claim: true,
|
||||
port_forwarding: true,
|
||||
daemonize: false,
|
||||
pid_file: None,
|
||||
stats_file: None,
|
||||
statsd_server: None,
|
||||
statsd_prefix: None,
|
||||
user: None,
|
||||
group: None,
|
||||
hook: None,
|
||||
hooks: HashMap::new()
|
||||
};
|
||||
let default_config_file =
|
||||
serde_yaml::from_str::<ConfigFile>(include_str!("../assets/example.net.disabled")).unwrap();
|
||||
default_config.merge_file(default_config_file);
|
||||
assert_eq!(default_config, Config::default());
|
||||
fn parse_example_config() {
|
||||
serde_yaml::from_str::<ConfigFile>(include_str!("../assets/example.net.disabled")).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
@ -0,0 +1,498 @@
|
|||
use super::{
|
||||
core::{test_speed, CryptoCore},
|
||||
init::{self, InitResult, InitState, CLOSING},
|
||||
rotate::RotationState
|
||||
};
|
||||
use crate::{
|
||||
error::Error,
|
||||
types::NodeId,
|
||||
util::{from_base62, to_base62, MsgBuffer}
|
||||
};
|
||||
use ring::{
|
||||
aead::{self, Algorithm, LessSafeKey, UnboundKey},
|
||||
agreement::{EphemeralPrivateKey, UnparsedPublicKey},
|
||||
pbkdf2,
|
||||
rand::{SecureRandom, SystemRandom},
|
||||
signature::{Ed25519KeyPair, KeyPair, ED25519_PUBLIC_KEY_LEN}
|
||||
};
|
||||
use smallvec::{smallvec, SmallVec};
|
||||
use std::{fmt::Debug, io::Read, num::NonZeroU32, sync::Arc, time::Duration};
|
||||
|
||||
|
||||
const SALT: &[u8; 32] = b"vpncloudVPNCLOUDvpncl0udVpnCloud";
|
||||
const INIT_MESSAGE_FIRST_BYTE: u8 = 0xff;
|
||||
const MESSAGE_TYPE_ROTATION: u8 = 0x10;
|
||||
|
||||
pub type Ed25519PublicKey = [u8; ED25519_PUBLIC_KEY_LEN];
|
||||
pub type EcdhPublicKey = UnparsedPublicKey<SmallVec<[u8; 96]>>;
|
||||
pub type EcdhPrivateKey = EphemeralPrivateKey;
|
||||
pub type Key = SmallVec<[u8; 32]>;
|
||||
|
||||
|
||||
const DEFAULT_ALGORITHMS: [&str; 3] = ["AES128", "AES256", "CHACHA20"];
|
||||
|
||||
#[cfg(test)]
|
||||
const SPEED_TEST_TIME: f32 = 0.02;
|
||||
#[cfg(not(test))]
|
||||
const SPEED_TEST_TIME: f32 = 0.1;
|
||||
|
||||
const ROTATE_INTERVAL: usize = 120;
|
||||
|
||||
|
||||
pub trait Payload: Debug + PartialEq + Sized {
|
||||
fn write_to(&self, buffer: &mut MsgBuffer);
|
||||
fn read_from<R: Read>(r: R) -> Result<Self, Error>;
|
||||
}
|
||||
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Algorithms {
|
||||
pub algorithm_speeds: SmallVec<[(&'static Algorithm, f32); 3]>,
|
||||
pub allow_unencrypted: bool
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize, Clone, PartialEq)]
|
||||
#[serde(rename_all = "kebab-case", deny_unknown_fields, default)]
|
||||
pub struct Config {
|
||||
pub password: Option<String>,
|
||||
pub private_key: Option<String>,
|
||||
pub public_key: Option<String>,
|
||||
pub trusted_keys: Vec<String>,
|
||||
pub algorithms: Vec<String>
|
||||
}
|
||||
|
||||
pub struct Crypto {
|
||||
node_id: NodeId,
|
||||
key_pair: Arc<Ed25519KeyPair>,
|
||||
trusted_keys: Arc<[Ed25519PublicKey]>,
|
||||
algorithms: Algorithms
|
||||
}
|
||||
|
||||
impl Crypto {
|
||||
pub fn new(node_id: NodeId, config: &Config) -> Result<Self, Error> {
|
||||
let key_pair = if let Some(priv_key) = &config.private_key {
|
||||
if let Some(pub_key) = &config.public_key {
|
||||
Self::parse_keypair(priv_key, pub_key)?
|
||||
} else {
|
||||
Self::parse_private_key(priv_key)?
|
||||
}
|
||||
} else if let Some(password) = &config.password {
|
||||
Self::keypair_from_password(password)
|
||||
} else {
|
||||
return Err(Error::InvalidConfig("Either private_key or password must be set"))
|
||||
};
|
||||
let mut trusted_keys = vec![];
|
||||
for tn in &config.trusted_keys {
|
||||
trusted_keys.push(Self::parse_public_key(tn)?);
|
||||
}
|
||||
if trusted_keys.is_empty() {
|
||||
info!("Trusted keys not set, trusting only own public key");
|
||||
let mut key = [0; ED25519_PUBLIC_KEY_LEN];
|
||||
key.clone_from_slice(key_pair.public_key().as_ref());
|
||||
trusted_keys.push(key);
|
||||
}
|
||||
let mut algos = Algorithms { algorithm_speeds: smallvec![], allow_unencrypted: false };
|
||||
let algorithms = config.algorithms.iter().map(|a| a as &str).collect::<Vec<_>>();
|
||||
let allowed = if algorithms.is_empty() { &DEFAULT_ALGORITHMS } else { &algorithms as &[&str] };
|
||||
let duration = Duration::from_secs_f32(SPEED_TEST_TIME);
|
||||
let mut speeds = Vec::new();
|
||||
for name in allowed {
|
||||
let algo = match &name.to_uppercase() as &str {
|
||||
"UNENCRYPTED" | "NONE" | "PLAIN" => {
|
||||
algos.allow_unencrypted = true;
|
||||
warn!("Crypto settings allow unencrypted connections");
|
||||
continue
|
||||
}
|
||||
"AES128" | "AES128_GCM" | "AES_128" | "AES_128_GCM" => &aead::AES_128_GCM,
|
||||
"AES256" | "AES256_GCM" | "AES_256" | "AES_256_GCM" => &aead::AES_256_GCM,
|
||||
"CHACHA" | "CHACHA20" | "CHACHA20_POLY1305" => &aead::CHACHA20_POLY1305,
|
||||
_ => return Err(Error::InvalidConfig("Unknown crypto method"))
|
||||
};
|
||||
let speed = test_speed(algo, &duration);
|
||||
algos.algorithm_speeds.push((algo, speed as f32));
|
||||
speeds.push((name, speed as f32));
|
||||
}
|
||||
if !speeds.is_empty() {
|
||||
info!(
|
||||
"Crypto speeds: {}",
|
||||
speeds.into_iter().map(|(a, s)| format!("{}: {:.1} MiB/s", a, s)).collect::<Vec<_>>().join(", ")
|
||||
);
|
||||
}
|
||||
Ok(Self {
|
||||
node_id,
|
||||
key_pair: Arc::new(key_pair),
|
||||
trusted_keys: trusted_keys.into_boxed_slice().into(),
|
||||
algorithms: algos
|
||||
})
|
||||
}
|
||||
|
||||
pub fn generate_keypair(password: Option<&str>) -> (String, String) {
|
||||
let mut bytes = [0; 32];
|
||||
match password {
|
||||
None => {
|
||||
let rng = SystemRandom::new();
|
||||
rng.fill(&mut bytes).unwrap();
|
||||
}
|
||||
Some(password) => {
|
||||
pbkdf2::derive(
|
||||
pbkdf2::PBKDF2_HMAC_SHA256,
|
||||
NonZeroU32::new(4096).unwrap(),
|
||||
SALT,
|
||||
password.as_bytes(),
|
||||
&mut bytes
|
||||
);
|
||||
}
|
||||
}
|
||||
let keypair = Ed25519KeyPair::from_seed_unchecked(&bytes).unwrap();
|
||||
let privkey = to_base62(&bytes);
|
||||
let pubkey = to_base62(keypair.public_key().as_ref());
|
||||
(privkey, pubkey)
|
||||
}
|
||||
|
||||
fn keypair_from_password(password: &str) -> Ed25519KeyPair {
|
||||
let mut key = [0; 32];
|
||||
pbkdf2::derive(pbkdf2::PBKDF2_HMAC_SHA256, NonZeroU32::new(4096).unwrap(), SALT, password.as_bytes(), &mut key);
|
||||
Ed25519KeyPair::from_seed_unchecked(&key).unwrap()
|
||||
}
|
||||
|
||||
fn parse_keypair(privkey: &str, pubkey: &str) -> Result<Ed25519KeyPair, Error> {
|
||||
let privkey = from_base62(privkey).map_err(|_| Error::InvalidConfig("Failed to parse private key"))?;
|
||||
let pubkey = from_base62(pubkey).map_err(|_| Error::InvalidConfig("Failed to parse public key"))?;
|
||||
let keypair = Ed25519KeyPair::from_seed_and_public_key(&privkey, &pubkey)
|
||||
.map_err(|_| Error::InvalidConfig("Keys rejected by crypto library"))?;
|
||||
Ok(keypair)
|
||||
}
|
||||
|
||||
fn parse_private_key(privkey: &str) -> Result<Ed25519KeyPair, Error> {
|
||||
let privkey = from_base62(privkey).map_err(|_| Error::InvalidConfig("Failed to parse private key"))?;
|
||||
let keypair = Ed25519KeyPair::from_seed_unchecked(&privkey)
|
||||
.map_err(|_| Error::InvalidConfig("Key rejected by crypto library"))?;
|
||||
Ok(keypair)
|
||||
}
|
||||
|
||||
fn parse_public_key(pubkey: &str) -> Result<Ed25519PublicKey, Error> {
|
||||
let pubkey = from_base62(pubkey).map_err(|_| Error::InvalidConfig("Failed to parse public key"))?;
|
||||
if pubkey.len() != ED25519_PUBLIC_KEY_LEN {
|
||||
return Err(Error::InvalidConfig("Failed to parse public key"))
|
||||
}
|
||||
let mut result = [0; ED25519_PUBLIC_KEY_LEN];
|
||||
result.clone_from_slice(&pubkey);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub fn peer_instance<P: Payload>(&self, payload: P) -> PeerCrypto<P> {
|
||||
PeerCrypto::new(
|
||||
self.node_id,
|
||||
payload,
|
||||
self.key_pair.clone(),
|
||||
self.trusted_keys.clone(),
|
||||
self.algorithms.clone()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum MessageResult<P: Payload> {
|
||||
Message(u8),
|
||||
Initialized(P),
|
||||
InitializedWithReply(P),
|
||||
Reply,
|
||||
None
|
||||
}
|
||||
|
||||
|
||||
pub struct PeerCrypto<P: Payload> {
|
||||
#[allow(dead_code)]
|
||||
node_id: NodeId,
|
||||
init: Option<InitState<P>>,
|
||||
rotation: Option<RotationState>,
|
||||
unencrypted: bool,
|
||||
core: Option<CryptoCore>,
|
||||
rotate_counter: usize
|
||||
}
|
||||
|
||||
impl<P: Payload> PeerCrypto<P> {
|
||||
pub fn new(
|
||||
node_id: NodeId, init_payload: P, key_pair: Arc<Ed25519KeyPair>, trusted_keys: Arc<[Ed25519PublicKey]>,
|
||||
algorithms: Algorithms
|
||||
) -> Self
|
||||
{
|
||||
Self {
|
||||
node_id,
|
||||
init: Some(InitState::new(node_id, init_payload, key_pair, trusted_keys, algorithms)),
|
||||
rotation: None,
|
||||
unencrypted: false,
|
||||
core: None,
|
||||
rotate_counter: 0
|
||||
}
|
||||
}
|
||||
|
||||
fn get_init(&mut self) -> Result<&mut InitState<P>, Error> {
|
||||
if let Some(init) = &mut self.init {
|
||||
Ok(init)
|
||||
} else {
|
||||
Err(Error::InvalidCryptoState("Initialization already finished"))
|
||||
}
|
||||
}
|
||||
|
||||
fn get_core(&mut self) -> Result<&mut CryptoCore, Error> {
|
||||
if let Some(core) = &mut self.core {
|
||||
Ok(core)
|
||||
} else {
|
||||
Err(Error::InvalidCryptoState("Crypto core not ready yet"))
|
||||
}
|
||||
}
|
||||
|
||||
fn get_rotation(&mut self) -> Result<&mut RotationState, Error> {
|
||||
if let Some(rotation) = &mut self.rotation {
|
||||
Ok(rotation)
|
||||
} else {
|
||||
Err(Error::InvalidCryptoState("Key rotation not initialized"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn initialize(&mut self, out: &mut MsgBuffer) -> Result<(), Error> {
|
||||
let init = self.get_init()?;
|
||||
if init.stage() != init::STAGE_PING {
|
||||
Err(Error::InvalidCryptoState("Initialization already ongoing"))
|
||||
} else {
|
||||
init.send_ping(out);
|
||||
out.prepend_byte(INIT_MESSAGE_FIRST_BYTE);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_init(&self) -> bool {
|
||||
self.init.is_some()
|
||||
}
|
||||
|
||||
pub fn is_ready(&self) -> bool {
|
||||
self.core.is_some()
|
||||
}
|
||||
|
||||
pub fn algorithm_name(&self) -> &'static str {
|
||||
if let Some(ref core) = self.core {
|
||||
let algo = core.algorithm();
|
||||
if algo == &aead::CHACHA20_POLY1305 {
|
||||
"CHACHA20"
|
||||
} else if algo == &aead::AES_128_GCM {
|
||||
"AES128"
|
||||
} else if algo == &aead::AES_256_GCM {
|
||||
"AES256"
|
||||
} else {
|
||||
unreachable!()
|
||||
}
|
||||
} else {
|
||||
"PLAIN"
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_init_message(&mut self, buffer: &mut MsgBuffer) -> Result<MessageResult<P>, Error> {
|
||||
let result = self.get_init()?.handle_init(buffer)?;
|
||||
if !buffer.is_empty() {
|
||||
buffer.prepend_byte(INIT_MESSAGE_FIRST_BYTE);
|
||||
}
|
||||
match result {
|
||||
InitResult::Continue => Ok(MessageResult::Reply),
|
||||
InitResult::Success { peer_payload, is_initiator } => {
|
||||
self.core = self.get_init()?.take_core();
|
||||
if self.core.is_none() {
|
||||
self.unencrypted = true;
|
||||
}
|
||||
if self.get_init()?.stage() == init::CLOSING {
|
||||
self.init = None
|
||||
}
|
||||
if self.core.is_some() {
|
||||
self.rotation = Some(RotationState::new(!is_initiator, buffer));
|
||||
}
|
||||
if !is_initiator {
|
||||
if self.unencrypted {
|
||||
return Ok(MessageResult::Initialized(peer_payload))
|
||||
}
|
||||
assert!(!buffer.is_empty());
|
||||
buffer.prepend_byte(MESSAGE_TYPE_ROTATION);
|
||||
self.encrypt_message(buffer)?;
|
||||
}
|
||||
Ok(MessageResult::InitializedWithReply(peer_payload))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_rotate_message(&mut self, data: &[u8]) -> Result<(), Error> {
|
||||
if self.unencrypted {
|
||||
return Ok(())
|
||||
}
|
||||
if let Some(rot) = self.get_rotation()?.handle_message(data)? {
|
||||
let core = self.get_core()?;
|
||||
let algo = core.algorithm();
|
||||
let key = LessSafeKey::new(UnboundKey::new(algo, &rot.key[..algo.key_len()]).unwrap());
|
||||
core.rotate_key(key, rot.id, rot.use_for_sending);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn encrypt_message(&mut self, buffer: &mut MsgBuffer) -> Result<(), Error> {
|
||||
if self.unencrypted {
|
||||
return Ok(())
|
||||
}
|
||||
self.get_core()?.encrypt(buffer);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn decrypt_message(&mut self, buffer: &mut MsgBuffer) -> Result<(), Error> {
|
||||
// HOT PATH
|
||||
if self.unencrypted {
|
||||
return Ok(())
|
||||
}
|
||||
self.get_core()?.decrypt(buffer)
|
||||
}
|
||||
|
||||
pub fn handle_message(&mut self, buffer: &mut MsgBuffer) -> Result<MessageResult<P>, Error> {
|
||||
// HOT PATH
|
||||
if buffer.is_empty() {
|
||||
return Err(Error::InvalidCryptoState("No message in buffer"))
|
||||
}
|
||||
if is_init_message(buffer.buffer()) {
|
||||
// COLD PATH
|
||||
debug!("Received init message");
|
||||
buffer.take_prefix();
|
||||
self.handle_init_message(buffer)
|
||||
} else {
|
||||
// HOT PATH
|
||||
debug!("Received encrypted message");
|
||||
self.decrypt_message(buffer)?;
|
||||
let msg_type = buffer.take_prefix();
|
||||
if msg_type == MESSAGE_TYPE_ROTATION {
|
||||
// COLD PATH
|
||||
debug!("Received rotation message");
|
||||
self.handle_rotate_message(buffer.buffer())?;
|
||||
buffer.clear();
|
||||
Ok(MessageResult::None)
|
||||
} else {
|
||||
Ok(MessageResult::Message(msg_type))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send_message(&mut self, type_: u8, buffer: &mut MsgBuffer) -> Result<(), Error> {
|
||||
// HOT PATH
|
||||
assert_ne!(type_, MESSAGE_TYPE_ROTATION);
|
||||
buffer.prepend_byte(type_);
|
||||
self.encrypt_message(buffer)
|
||||
}
|
||||
|
||||
pub fn every_second(&mut self, out: &mut MsgBuffer) -> Result<MessageResult<P>, Error> {
|
||||
out.clear();
|
||||
if let Some(ref mut core) = self.core {
|
||||
core.every_second()
|
||||
}
|
||||
if let Some(ref mut init) = self.init {
|
||||
init.every_second(out)?;
|
||||
}
|
||||
if self.init.as_ref().map(|i| i.stage()).unwrap_or(CLOSING) == CLOSING {
|
||||
self.init = None
|
||||
}
|
||||
if !out.is_empty() {
|
||||
out.prepend_byte(INIT_MESSAGE_FIRST_BYTE);
|
||||
return Ok(MessageResult::Reply)
|
||||
}
|
||||
if let Some(ref mut rotate) = self.rotation {
|
||||
self.rotate_counter += 1;
|
||||
if self.rotate_counter >= ROTATE_INTERVAL {
|
||||
self.rotate_counter = 0;
|
||||
if let Some(rot) = rotate.cycle(out) {
|
||||
let core = self.get_core()?;
|
||||
let algo = core.algorithm();
|
||||
let key = LessSafeKey::new(UnboundKey::new(algo, &rot.key[..algo.key_len()]).unwrap());
|
||||
core.rotate_key(key, rot.id, rot.use_for_sending);
|
||||
}
|
||||
if !out.is_empty() {
|
||||
out.prepend_byte(MESSAGE_TYPE_ROTATION);
|
||||
self.encrypt_message(out)?;
|
||||
return Ok(MessageResult::Reply)
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(MessageResult::None)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_init_message(msg: &[u8]) -> bool {
|
||||
// HOT PATH
|
||||
!msg.is_empty() && msg[0] == INIT_MESSAGE_FIRST_BYTE
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
use crate::types::NODE_ID_BYTES;
|
||||
|
||||
fn create_node(config: &Config) -> PeerCrypto<Vec<u8>> {
|
||||
let rng = SystemRandom::new();
|
||||
let mut node_id = [0; NODE_ID_BYTES];
|
||||
rng.fill(&mut node_id).unwrap();
|
||||
let crypto = Crypto::new(node_id, config).unwrap();
|
||||
crypto.peer_instance(vec![])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normal() {
|
||||
let config = Config { password: Some("test".to_string()), ..Default::default() };
|
||||
let mut node1 = create_node(&config);
|
||||
let mut node2 = create_node(&config);
|
||||
let mut msg = MsgBuffer::new(16);
|
||||
|
||||
node1.initialize(&mut msg).unwrap();
|
||||
assert!(!msg.is_empty());
|
||||
|
||||
debug!("Node1 -> Node2");
|
||||
let res = node2.handle_message(&mut msg).unwrap();
|
||||
assert_eq!(res, MessageResult::Reply);
|
||||
assert!(!msg.is_empty());
|
||||
|
||||
debug!("Node1 <- Node2");
|
||||
let res = node1.handle_message(&mut msg).unwrap();
|
||||
assert_eq!(res, MessageResult::InitializedWithReply(vec![]));
|
||||
assert!(!msg.is_empty());
|
||||
|
||||
debug!("Node1 -> Node2");
|
||||
let res = node2.handle_message(&mut msg).unwrap();
|
||||
assert_eq!(res, MessageResult::InitializedWithReply(vec![]));
|
||||
assert!(!msg.is_empty());
|
||||
|
||||
debug!("Node1 <- Node2");
|
||||
let res = node1.handle_message(&mut msg).unwrap();
|
||||
assert_eq!(res, MessageResult::None);
|
||||
assert!(msg.is_empty());
|
||||
|
||||
let mut buffer = MsgBuffer::new(16);
|
||||
let rng = SystemRandom::new();
|
||||
buffer.set_length(1000);
|
||||
rng.fill(buffer.message_mut()).unwrap();
|
||||
for _ in 0..1000 {
|
||||
node1.send_message(1, &mut buffer).unwrap();
|
||||
let res = node2.handle_message(&mut buffer).unwrap();
|
||||
assert_eq!(res, MessageResult::Message(1));
|
||||
|
||||
match node1.every_second(&mut msg).unwrap() {
|
||||
MessageResult::None => (),
|
||||
MessageResult::Reply => {
|
||||
let res = node2.handle_message(&mut msg).unwrap();
|
||||
assert_eq!(res, MessageResult::None);
|
||||
}
|
||||
other => assert_eq!(other, MessageResult::None)
|
||||
}
|
||||
match node2.every_second(&mut msg).unwrap() {
|
||||
MessageResult::None => (),
|
||||
MessageResult::Reply => {
|
||||
let res = node1.handle_message(&mut msg).unwrap();
|
||||
assert_eq!(res, MessageResult::None);
|
||||
}
|
||||
other => assert_eq!(other, MessageResult::None)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,3 +1,7 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
// This module implements a crypto core for encrypting and decrypting message streams
|
||||
//
|
||||
// The crypto core only encrypts and decrypts messages, using given keys. Negotiating and rotating the keys is out of
|
||||
|
@ -49,7 +53,7 @@ use std::{
|
|||
time::{Duration, Instant}
|
||||
};
|
||||
|
||||
use super::{Error, MsgBuffer};
|
||||
use crate::{error::Error, util::MsgBuffer};
|
||||
|
||||
|
||||
const NONCE_LEN: usize = 12;
|
||||
|
|
|
@ -1,3 +1,7 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
// This module implements a 3-way handshake to initialize an authenticated and encrypted connection.
|
||||
//
|
||||
// The handshake assumes that each node has a asymmetric Curve 25519 key pair as well as a list of trusted public keys
|
||||
|
@ -53,9 +57,9 @@
|
|||
|
||||
use super::{
|
||||
core::{CryptoCore, EXTRA_LEN},
|
||||
Algorithms, EcdhPrivateKey, EcdhPublicKey, Ed25519PublicKey, Error, MsgBuffer, Payload
|
||||
Algorithms, EcdhPrivateKey, EcdhPublicKey, Ed25519PublicKey, Payload
|
||||
};
|
||||
use crate::types::NodeId;
|
||||
use crate::{error::Error, types::NodeId, util::MsgBuffer};
|
||||
use byteorder::{NetworkEndian, ReadBytesExt, WriteBytesExt};
|
||||
use ring::{
|
||||
aead::{Algorithm, LessSafeKey, UnboundKey, AES_128_GCM, AES_256_GCM, CHACHA20_POLY1305},
|
||||
|
@ -400,8 +404,7 @@ impl<P: Payload> InitState<P> {
|
|||
pub fn new(
|
||||
node_id: NodeId, payload: P, key_pair: Arc<Ed25519KeyPair>, trusted_keys: Arc<[Ed25519PublicKey]>,
|
||||
algorithms: Algorithms
|
||||
) -> Self
|
||||
{
|
||||
) -> Self {
|
||||
let mut hash = [0; SALTED_NODE_ID_HASH_LEN];
|
||||
let rng = SystemRandom::new();
|
||||
rng.fill(&mut hash[0..4]).unwrap();
|
||||
|
|
|
@ -1,504 +1,11 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
mod common;
|
||||
mod core;
|
||||
mod init;
|
||||
mod rotate;
|
||||
|
||||
pub use common::*;
|
||||
pub use self::core::{EXTRA_LEN, TAG_LEN};
|
||||
use self::{
|
||||
core::{test_speed, CryptoCore},
|
||||
init::{InitResult, InitState, CLOSING},
|
||||
rotate::RotationState
|
||||
};
|
||||
use crate::{
|
||||
error::Error,
|
||||
types::NodeId,
|
||||
util::{from_base62, to_base62, MsgBuffer}
|
||||
};
|
||||
use ring::{
|
||||
aead::{self, Algorithm, LessSafeKey, UnboundKey},
|
||||
agreement::{EphemeralPrivateKey, UnparsedPublicKey},
|
||||
pbkdf2,
|
||||
rand::{SecureRandom, SystemRandom},
|
||||
signature::{Ed25519KeyPair, KeyPair, ED25519_PUBLIC_KEY_LEN}
|
||||
};
|
||||
use smallvec::{smallvec, SmallVec};
|
||||
use std::{fmt::Debug, io::Read, num::NonZeroU32, sync::Arc, time::Duration};
|
||||
use thiserror::Error;
|
||||
|
||||
|
||||
const SALT: &[u8; 32] = b"vpncloudVPNCLOUDvpncl0udVpnCloud";
|
||||
const INIT_MESSAGE_FIRST_BYTE: u8 = 0xff;
|
||||
const MESSAGE_TYPE_ROTATION: u8 = 0x10;
|
||||
|
||||
pub type Ed25519PublicKey = [u8; ED25519_PUBLIC_KEY_LEN];
|
||||
pub type EcdhPublicKey = UnparsedPublicKey<SmallVec<[u8; 96]>>;
|
||||
pub type EcdhPrivateKey = EphemeralPrivateKey;
|
||||
pub type Key = SmallVec<[u8; 32]>;
|
||||
|
||||
|
||||
const DEFAULT_ALGORITHMS: [&str; 3] = ["AES128", "AES256", "CHACHA20"];
|
||||
|
||||
#[cfg(test)]
|
||||
const SPEED_TEST_TIME: f32 = 0.02;
|
||||
#[cfg(not(test))]
|
||||
const SPEED_TEST_TIME: f32 = 0.1;
|
||||
|
||||
const ROTATE_INTERVAL: usize = 120;
|
||||
|
||||
|
||||
pub trait Payload: Debug + PartialEq + Sized {
|
||||
fn write_to(&self, buffer: &mut MsgBuffer);
|
||||
fn read_from<R: Read>(r: R) -> Result<Self, Error>;
|
||||
}
|
||||
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Algorithms {
|
||||
pub algorithm_speeds: SmallVec<[(&'static Algorithm, f32); 3]>,
|
||||
pub allow_unencrypted: bool
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize, Clone, PartialEq)]
|
||||
#[serde(rename_all = "kebab-case", deny_unknown_fields, default)]
|
||||
pub struct Config {
|
||||
pub password: Option<String>,
|
||||
pub private_key: Option<String>,
|
||||
pub public_key: Option<String>,
|
||||
pub trusted_keys: Vec<String>,
|
||||
pub algorithms: Vec<String>
|
||||
}
|
||||
|
||||
pub struct Crypto {
|
||||
node_id: NodeId,
|
||||
key_pair: Arc<Ed25519KeyPair>,
|
||||
trusted_keys: Arc<[Ed25519PublicKey]>,
|
||||
algorithms: Algorithms
|
||||
}
|
||||
|
||||
impl Crypto {
|
||||
pub fn new(node_id: NodeId, config: &Config) -> Result<Self, Error> {
|
||||
let key_pair = if let Some(priv_key) = &config.private_key {
|
||||
if let Some(pub_key) = &config.public_key {
|
||||
Self::parse_keypair(priv_key, pub_key)?
|
||||
} else {
|
||||
Self::parse_private_key(priv_key)?
|
||||
}
|
||||
} else if let Some(password) = &config.password {
|
||||
Self::keypair_from_password(password)
|
||||
} else {
|
||||
return Err(Error::InvalidConfig("Either private_key or password must be set"))
|
||||
};
|
||||
let mut trusted_keys = vec![];
|
||||
for tn in &config.trusted_keys {
|
||||
trusted_keys.push(Self::parse_public_key(tn)?);
|
||||
}
|
||||
if trusted_keys.is_empty() {
|
||||
info!("Trusted keys not set, trusting only own public key");
|
||||
let mut key = [0; ED25519_PUBLIC_KEY_LEN];
|
||||
key.clone_from_slice(key_pair.public_key().as_ref());
|
||||
trusted_keys.push(key);
|
||||
}
|
||||
let mut algos = Algorithms { algorithm_speeds: smallvec![], allow_unencrypted: false };
|
||||
let algorithms = config.algorithms.iter().map(|a| a as &str).collect::<Vec<_>>();
|
||||
let allowed = if algorithms.is_empty() { &DEFAULT_ALGORITHMS } else { &algorithms as &[&str] };
|
||||
let duration = Duration::from_secs_f32(SPEED_TEST_TIME);
|
||||
let mut speeds = Vec::new();
|
||||
for name in allowed {
|
||||
let algo = match &name.to_uppercase() as &str {
|
||||
"UNENCRYPTED" | "NONE" | "PLAIN" => {
|
||||
algos.allow_unencrypted = true;
|
||||
warn!("Crypto settings allow unencrypted connections");
|
||||
continue
|
||||
}
|
||||
"AES128" | "AES128_GCM" | "AES_128" | "AES_128_GCM" => &aead::AES_128_GCM,
|
||||
"AES256" | "AES256_GCM" | "AES_256" | "AES_256_GCM" => &aead::AES_256_GCM,
|
||||
"CHACHA" | "CHACHA20" | "CHACHA20_POLY1305" => &aead::CHACHA20_POLY1305,
|
||||
_ => return Err(Error::InvalidConfig("Unknown crypto method"))
|
||||
};
|
||||
let speed = test_speed(algo, &duration);
|
||||
algos.algorithm_speeds.push((algo, speed as f32));
|
||||
speeds.push((name, speed as f32));
|
||||
}
|
||||
if !speeds.is_empty() {
|
||||
info!(
|
||||
"Crypto speeds: {}",
|
||||
speeds.into_iter().map(|(a, s)| format!("{}: {:.1} MiB/s", a, s)).collect::<Vec<_>>().join(", ")
|
||||
);
|
||||
}
|
||||
Ok(Self {
|
||||
node_id,
|
||||
key_pair: Arc::new(key_pair),
|
||||
trusted_keys: trusted_keys.into_boxed_slice().into(),
|
||||
algorithms: algos
|
||||
})
|
||||
}
|
||||
|
||||
pub fn generate_keypair(password: Option<&str>) -> (String, String) {
|
||||
let mut bytes = [0; 32];
|
||||
match password {
|
||||
None => {
|
||||
let rng = SystemRandom::new();
|
||||
rng.fill(&mut bytes).unwrap();
|
||||
}
|
||||
Some(password) => {
|
||||
pbkdf2::derive(
|
||||
pbkdf2::PBKDF2_HMAC_SHA256,
|
||||
NonZeroU32::new(4096).unwrap(),
|
||||
SALT,
|
||||
password.as_bytes(),
|
||||
&mut bytes
|
||||
);
|
||||
}
|
||||
}
|
||||
let keypair = Ed25519KeyPair::from_seed_unchecked(&bytes).unwrap();
|
||||
let privkey = to_base62(&bytes);
|
||||
let pubkey = to_base62(keypair.public_key().as_ref());
|
||||
(privkey, pubkey)
|
||||
}
|
||||
|
||||
fn keypair_from_password(password: &str) -> Ed25519KeyPair {
|
||||
let mut key = [0; 32];
|
||||
pbkdf2::derive(pbkdf2::PBKDF2_HMAC_SHA256, NonZeroU32::new(4096).unwrap(), SALT, password.as_bytes(), &mut key);
|
||||
Ed25519KeyPair::from_seed_unchecked(&key).unwrap()
|
||||
}
|
||||
|
||||
fn parse_keypair(privkey: &str, pubkey: &str) -> Result<Ed25519KeyPair, Error> {
|
||||
let privkey = from_base62(privkey).map_err(|_| Error::InvalidConfig("Failed to parse private key"))?;
|
||||
let pubkey = from_base62(pubkey).map_err(|_| Error::InvalidConfig("Failed to parse public key"))?;
|
||||
let keypair = Ed25519KeyPair::from_seed_and_public_key(&privkey, &pubkey)
|
||||
.map_err(|_| Error::InvalidConfig("Keys rejected by crypto library"))?;
|
||||
Ok(keypair)
|
||||
}
|
||||
|
||||
fn parse_private_key(privkey: &str) -> Result<Ed25519KeyPair, Error> {
|
||||
let privkey = from_base62(privkey).map_err(|_| Error::InvalidConfig("Failed to parse private key"))?;
|
||||
let keypair = Ed25519KeyPair::from_seed_unchecked(&privkey)
|
||||
.map_err(|_| Error::InvalidConfig("Key rejected by crypto library"))?;
|
||||
Ok(keypair)
|
||||
}
|
||||
|
||||
fn parse_public_key(pubkey: &str) -> Result<Ed25519PublicKey, Error> {
|
||||
let pubkey = from_base62(pubkey).map_err(|_| Error::InvalidConfig("Failed to parse public key"))?;
|
||||
if pubkey.len() != ED25519_PUBLIC_KEY_LEN {
|
||||
return Err(Error::InvalidConfig("Failed to parse public key"))
|
||||
}
|
||||
let mut result = [0; ED25519_PUBLIC_KEY_LEN];
|
||||
result.clone_from_slice(&pubkey);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub fn peer_instance<P: Payload>(&self, payload: P) -> PeerCrypto<P> {
|
||||
PeerCrypto::new(
|
||||
self.node_id,
|
||||
payload,
|
||||
self.key_pair.clone(),
|
||||
self.trusted_keys.clone(),
|
||||
self.algorithms.clone()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum MessageResult<P: Payload> {
|
||||
Message(u8),
|
||||
Initialized(P),
|
||||
InitializedWithReply(P),
|
||||
Reply,
|
||||
None
|
||||
}
|
||||
|
||||
|
||||
pub struct PeerCrypto<P: Payload> {
|
||||
#[allow(dead_code)]
|
||||
node_id: NodeId,
|
||||
init: Option<InitState<P>>,
|
||||
rotation: Option<RotationState>,
|
||||
unencrypted: bool,
|
||||
core: Option<CryptoCore>,
|
||||
rotate_counter: usize
|
||||
}
|
||||
|
||||
impl<P: Payload> PeerCrypto<P> {
|
||||
pub fn new(
|
||||
node_id: NodeId, init_payload: P, key_pair: Arc<Ed25519KeyPair>, trusted_keys: Arc<[Ed25519PublicKey]>,
|
||||
algorithms: Algorithms
|
||||
) -> Self
|
||||
{
|
||||
Self {
|
||||
node_id,
|
||||
init: Some(InitState::new(node_id, init_payload, key_pair, trusted_keys, algorithms)),
|
||||
rotation: None,
|
||||
unencrypted: false,
|
||||
core: None,
|
||||
rotate_counter: 0
|
||||
}
|
||||
}
|
||||
|
||||
fn get_init(&mut self) -> Result<&mut InitState<P>, Error> {
|
||||
if let Some(init) = &mut self.init {
|
||||
Ok(init)
|
||||
} else {
|
||||
Err(Error::InvalidCryptoState("Initialization already finished"))
|
||||
}
|
||||
}
|
||||
|
||||
fn get_core(&mut self) -> Result<&mut CryptoCore, Error> {
|
||||
if let Some(core) = &mut self.core {
|
||||
Ok(core)
|
||||
} else {
|
||||
Err(Error::InvalidCryptoState("Crypto core not ready yet"))
|
||||
}
|
||||
}
|
||||
|
||||
fn get_rotation(&mut self) -> Result<&mut RotationState, Error> {
|
||||
if let Some(rotation) = &mut self.rotation {
|
||||
Ok(rotation)
|
||||
} else {
|
||||
Err(Error::InvalidCryptoState("Key rotation not initialized"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn initialize(&mut self, out: &mut MsgBuffer) -> Result<(), Error> {
|
||||
let init = self.get_init()?;
|
||||
if init.stage() != init::STAGE_PING {
|
||||
Err(Error::InvalidCryptoState("Initialization already ongoing"))
|
||||
} else {
|
||||
init.send_ping(out);
|
||||
out.prepend_byte(INIT_MESSAGE_FIRST_BYTE);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_init(&self) -> bool {
|
||||
self.init.is_some()
|
||||
}
|
||||
|
||||
pub fn is_ready(&self) -> bool {
|
||||
self.core.is_some()
|
||||
}
|
||||
|
||||
pub fn algorithm_name(&self) -> &'static str {
|
||||
if let Some(ref core) = self.core {
|
||||
let algo = core.algorithm();
|
||||
if algo == &aead::CHACHA20_POLY1305 {
|
||||
"CHACHA20"
|
||||
} else if algo == &aead::AES_128_GCM {
|
||||
"AES128"
|
||||
} else if algo == &aead::AES_256_GCM {
|
||||
"AES256"
|
||||
} else {
|
||||
unreachable!()
|
||||
}
|
||||
} else {
|
||||
"PLAIN"
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_init_message(&mut self, buffer: &mut MsgBuffer) -> Result<MessageResult<P>, Error> {
|
||||
let result = self.get_init()?.handle_init(buffer)?;
|
||||
if !buffer.is_empty() {
|
||||
buffer.prepend_byte(INIT_MESSAGE_FIRST_BYTE);
|
||||
}
|
||||
match result {
|
||||
InitResult::Continue => Ok(MessageResult::Reply),
|
||||
InitResult::Success { peer_payload, is_initiator } => {
|
||||
self.core = self.get_init()?.take_core();
|
||||
if self.core.is_none() {
|
||||
self.unencrypted = true;
|
||||
}
|
||||
if self.get_init()?.stage() == init::CLOSING {
|
||||
self.init = None
|
||||
}
|
||||
if self.core.is_some() {
|
||||
self.rotation = Some(RotationState::new(!is_initiator, buffer));
|
||||
}
|
||||
if !is_initiator {
|
||||
if self.unencrypted {
|
||||
return Ok(MessageResult::Initialized(peer_payload))
|
||||
}
|
||||
assert!(!buffer.is_empty());
|
||||
buffer.prepend_byte(MESSAGE_TYPE_ROTATION);
|
||||
self.encrypt_message(buffer)?;
|
||||
}
|
||||
Ok(MessageResult::InitializedWithReply(peer_payload))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_rotate_message(&mut self, data: &[u8]) -> Result<(), Error> {
|
||||
if self.unencrypted {
|
||||
return Ok(())
|
||||
}
|
||||
if let Some(rot) = self.get_rotation()?.handle_message(data)? {
|
||||
let core = self.get_core()?;
|
||||
let algo = core.algorithm();
|
||||
let key = LessSafeKey::new(UnboundKey::new(algo, &rot.key[..algo.key_len()]).unwrap());
|
||||
core.rotate_key(key, rot.id, rot.use_for_sending);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn encrypt_message(&mut self, buffer: &mut MsgBuffer) -> Result<(), Error> {
|
||||
if self.unencrypted {
|
||||
return Ok(())
|
||||
}
|
||||
self.get_core()?.encrypt(buffer);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn decrypt_message(&mut self, buffer: &mut MsgBuffer) -> Result<(), Error> {
|
||||
// HOT PATH
|
||||
if self.unencrypted {
|
||||
return Ok(())
|
||||
}
|
||||
self.get_core()?.decrypt(buffer)
|
||||
}
|
||||
|
||||
pub fn handle_message(&mut self, buffer: &mut MsgBuffer) -> Result<MessageResult<P>, Error> {
|
||||
// HOT PATH
|
||||
if buffer.is_empty() {
|
||||
return Err(Error::InvalidCryptoState("No message in buffer"))
|
||||
}
|
||||
if is_init_message(buffer.buffer()) {
|
||||
// COLD PATH
|
||||
debug!("Received init message");
|
||||
buffer.take_prefix();
|
||||
self.handle_init_message(buffer)
|
||||
} else {
|
||||
// HOT PATH
|
||||
debug!("Received encrypted message");
|
||||
self.decrypt_message(buffer)?;
|
||||
let msg_type = buffer.take_prefix();
|
||||
if msg_type == MESSAGE_TYPE_ROTATION {
|
||||
// COLD PATH
|
||||
debug!("Received rotation message");
|
||||
self.handle_rotate_message(buffer.buffer())?;
|
||||
buffer.clear();
|
||||
Ok(MessageResult::None)
|
||||
} else {
|
||||
Ok(MessageResult::Message(msg_type))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send_message(&mut self, type_: u8, buffer: &mut MsgBuffer) -> Result<(), Error> {
|
||||
// HOT PATH
|
||||
assert_ne!(type_, MESSAGE_TYPE_ROTATION);
|
||||
buffer.prepend_byte(type_);
|
||||
self.encrypt_message(buffer)
|
||||
}
|
||||
|
||||
pub fn every_second(&mut self, out: &mut MsgBuffer) -> Result<MessageResult<P>, Error> {
|
||||
out.clear();
|
||||
if let Some(ref mut core) = self.core {
|
||||
core.every_second()
|
||||
}
|
||||
if let Some(ref mut init) = self.init {
|
||||
init.every_second(out)?;
|
||||
}
|
||||
if self.init.as_ref().map(|i| i.stage()).unwrap_or(CLOSING) == CLOSING {
|
||||
self.init = None
|
||||
}
|
||||
if !out.is_empty() {
|
||||
out.prepend_byte(INIT_MESSAGE_FIRST_BYTE);
|
||||
return Ok(MessageResult::Reply)
|
||||
}
|
||||
if let Some(ref mut rotate) = self.rotation {
|
||||
self.rotate_counter += 1;
|
||||
if self.rotate_counter >= ROTATE_INTERVAL {
|
||||
self.rotate_counter = 0;
|
||||
if let Some(rot) = rotate.cycle(out) {
|
||||
let core = self.get_core()?;
|
||||
let algo = core.algorithm();
|
||||
let key = LessSafeKey::new(UnboundKey::new(algo, &rot.key[..algo.key_len()]).unwrap());
|
||||
core.rotate_key(key, rot.id, rot.use_for_sending);
|
||||
}
|
||||
if !out.is_empty() {
|
||||
out.prepend_byte(MESSAGE_TYPE_ROTATION);
|
||||
self.encrypt_message(out)?;
|
||||
return Ok(MessageResult::Reply)
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(MessageResult::None)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_init_message(msg: &[u8]) -> bool {
|
||||
// HOT PATH
|
||||
!msg.is_empty() && msg[0] == INIT_MESSAGE_FIRST_BYTE
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
use crate::types::NODE_ID_BYTES;
|
||||
|
||||
fn create_node(config: &Config) -> PeerCrypto<Vec<u8>> {
|
||||
let rng = SystemRandom::new();
|
||||
let mut node_id = [0; NODE_ID_BYTES];
|
||||
rng.fill(&mut node_id).unwrap();
|
||||
let crypto = Crypto::new(node_id, config).unwrap();
|
||||
crypto.peer_instance(vec![])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normal() {
|
||||
let config = Config { password: Some("test".to_string()), ..Default::default() };
|
||||
let mut node1 = create_node(&config);
|
||||
let mut node2 = create_node(&config);
|
||||
let mut msg = MsgBuffer::new(16);
|
||||
|
||||
node1.initialize(&mut msg).unwrap();
|
||||
assert!(!msg.is_empty());
|
||||
|
||||
debug!("Node1 -> Node2");
|
||||
let res = node2.handle_message(&mut msg).unwrap();
|
||||
assert_eq!(res, MessageResult::Reply);
|
||||
assert!(!msg.is_empty());
|
||||
|
||||
debug!("Node1 <- Node2");
|
||||
let res = node1.handle_message(&mut msg).unwrap();
|
||||
assert_eq!(res, MessageResult::InitializedWithReply(vec![]));
|
||||
assert!(!msg.is_empty());
|
||||
|
||||
debug!("Node1 -> Node2");
|
||||
let res = node2.handle_message(&mut msg).unwrap();
|
||||
assert_eq!(res, MessageResult::InitializedWithReply(vec![]));
|
||||
assert!(!msg.is_empty());
|
||||
|
||||
debug!("Node1 <- Node2");
|
||||
let res = node1.handle_message(&mut msg).unwrap();
|
||||
assert_eq!(res, MessageResult::None);
|
||||
assert!(msg.is_empty());
|
||||
|
||||
let mut buffer = MsgBuffer::new(16);
|
||||
let rng = SystemRandom::new();
|
||||
buffer.set_length(1000);
|
||||
rng.fill(buffer.message_mut()).unwrap();
|
||||
for _ in 0..1000 {
|
||||
node1.send_message(1, &mut buffer).unwrap();
|
||||
let res = node2.handle_message(&mut buffer).unwrap();
|
||||
assert_eq!(res, MessageResult::Message(1));
|
||||
|
||||
match node1.every_second(&mut msg).unwrap() {
|
||||
MessageResult::None => (),
|
||||
MessageResult::Reply => {
|
||||
let res = node2.handle_message(&mut msg).unwrap();
|
||||
assert_eq!(res, MessageResult::None);
|
||||
}
|
||||
other => assert_eq!(other, MessageResult::None)
|
||||
}
|
||||
match node2.every_second(&mut msg).unwrap() {
|
||||
MessageResult::None => (),
|
||||
MessageResult::Reply => {
|
||||
let res = node1.handle_message(&mut msg).unwrap();
|
||||
assert_eq!(res, MessageResult::None);
|
||||
}
|
||||
other => assert_eq!(other, MessageResult::None)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,3 +1,7 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
// This module implements a turn based key rotation.
|
||||
//
|
||||
// The main idea is that both peers periodically create ecdh key pairs and exchange their public keys to create
|
||||
|
@ -25,7 +29,8 @@
|
|||
//
|
||||
// The whole communication is sent via the crypto stream and is therefore encrypted and protected against tampering.
|
||||
|
||||
use super::{Error, Key, MsgBuffer};
|
||||
use super::Key;
|
||||
use crate::{error::Error, util::MsgBuffer};
|
||||
use byteorder::{NetworkEndian, ReadBytesExt, WriteBytesExt};
|
||||
use ring::{
|
||||
agreement::{agree_ephemeral, EphemeralPrivateKey, UnparsedPublicKey, X25519},
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2020 Dennis Schwerdel
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
use std::{
|
||||
|
@ -344,7 +344,7 @@ impl Device for MockDevice {
|
|||
}
|
||||
|
||||
fn write(&mut self, buffer: &mut MsgBuffer) -> Result<(), Error> {
|
||||
self.outbound.push_back(buffer.message().to_owned());
|
||||
self.outbound.push_back(buffer.message().into());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
@ -355,7 +355,7 @@ impl Device for MockDevice {
|
|||
|
||||
impl Default for MockDevice {
|
||||
fn default() -> Self {
|
||||
Self { outbound: VecDeque::new(), inbound: VecDeque::new() }
|
||||
Self { outbound: VecDeque::with_capacity(10), inbound: VecDeque::with_capacity(10) }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,3 +1,7 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
use std::io;
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2020 Dennis Schwerdel
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
#[macro_use] extern crate log;
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2020 Dennis Schwerdel
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
use crate::{
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2020 Dennis Schwerdel
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
use std::{
|
||||
|
@ -93,8 +93,8 @@ impl MockSocket {
|
|||
nat: Self::get_nat(),
|
||||
nat_peers: HashMap::new(),
|
||||
address,
|
||||
outbound: VecDeque::new(),
|
||||
inbound: VecDeque::new()
|
||||
outbound: VecDeque::with_capacity(10),
|
||||
inbound: VecDeque::with_capacity(10)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -149,7 +149,7 @@ impl Socket for MockSocket {
|
|||
}
|
||||
|
||||
fn send(&mut self, data: &[u8], addr: SocketAddr) -> Result<usize, io::Error> {
|
||||
self.outbound.push_back((addr, data.to_owned()));
|
||||
self.outbound.push_back((addr, data.into()));
|
||||
if self.nat {
|
||||
self.nat_peers.insert(addr, MockTimeSource::now() + 300);
|
||||
}
|
||||
|
|
|
@ -1,3 +1,7 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
use super::{device::Type, types::Mode, util::Duration};
|
||||
use crate::config::{ConfigFile, ConfigFileBeacon, ConfigFileDevice, ConfigFileStatsd, CryptoConfig};
|
||||
use std::collections::HashMap;
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2020 Dennis Schwerdel
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
use crate::{error::Error, types::Address};
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2020 Dennis Schwerdel
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
use std::{io, os::unix::io::RawFd};
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2020 Dennis Schwerdel
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2020 Dennis Schwerdel
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
#[cfg(feature = "nat")]
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2020 Dennis Schwerdel
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
use fnv::FnvHasher;
|
||||
|
|
|
@ -0,0 +1,214 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
use std::{
|
||||
collections::{HashMap, VecDeque},
|
||||
io::Write,
|
||||
net::SocketAddr,
|
||||
sync::{
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
Once
|
||||
}
|
||||
};
|
||||
|
||||
pub use crate::{
|
||||
cloud::GenericCloud,
|
||||
config::{Config, CryptoConfig},
|
||||
device::{MockDevice, Type},
|
||||
net::MockSocket,
|
||||
payload::{Frame, Packet, Protocol},
|
||||
types::Range,
|
||||
util::{MockTimeSource, Time, TimeSource}
|
||||
};
|
||||
|
||||
|
||||
static INIT_LOGGER: Once = Once::new();
|
||||
|
||||
pub fn init_debug_logger() {
|
||||
INIT_LOGGER.call_once(|| {
|
||||
log::set_boxed_logger(Box::new(DebugLogger)).unwrap();
|
||||
log::set_max_level(log::LevelFilter::Debug);
|
||||
})
|
||||
}
|
||||
|
||||
static CURRENT_NODE: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
struct DebugLogger;
|
||||
|
||||
impl DebugLogger {
|
||||
pub fn set_node(node: usize) {
|
||||
CURRENT_NODE.store(node, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
impl log::Log for DebugLogger {
|
||||
#[inline]
|
||||
fn enabled(&self, metadata: &log::Metadata) -> bool {
|
||||
log::max_level() > metadata.level()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn log(&self, record: &log::Record) {
|
||||
if self.enabled(record.metadata()) {
|
||||
eprintln!("Node {} - {} - {}", CURRENT_NODE.load(Ordering::SeqCst), record.level(), record.args());
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn flush(&self) {
|
||||
std::io::stderr().flush().expect("Failed to flush")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
type TestNode<P> = GenericCloud<MockDevice, P, MockSocket, MockTimeSource>;
|
||||
|
||||
pub struct Simulator<P: Protocol> {
|
||||
next_port: u16,
|
||||
nodes: HashMap<SocketAddr, TestNode<P>>,
|
||||
messages: VecDeque<(SocketAddr, SocketAddr, Vec<u8>)>
|
||||
}
|
||||
|
||||
pub type TapSimulator = Simulator<Frame>;
|
||||
#[allow(dead_code)]
|
||||
pub type TunSimulator = Simulator<Packet>;
|
||||
|
||||
|
||||
impl<P: Protocol> Simulator<P> {
|
||||
pub fn new() -> Self {
|
||||
init_debug_logger();
|
||||
MockTimeSource::set_time(0);
|
||||
Self { next_port: 1, nodes: HashMap::default(), messages: VecDeque::with_capacity(10) }
|
||||
}
|
||||
|
||||
pub fn add_node(&mut self, nat: bool, config: &Config) -> SocketAddr {
|
||||
let mut config = config.clone();
|
||||
MockSocket::set_nat(nat);
|
||||
config.listen = format!("[::]:{}", self.next_port);
|
||||
let addr = config.listen.parse::<SocketAddr>().unwrap();
|
||||
if config.crypto.password.is_none() && config.crypto.private_key.is_none() {
|
||||
config.crypto.password = Some("test123".to_string())
|
||||
}
|
||||
DebugLogger::set_node(self.next_port as usize);
|
||||
self.next_port += 1;
|
||||
let node = TestNode::new(&config, MockSocket::new(addr), MockDevice::new(), None, None);
|
||||
DebugLogger::set_node(0);
|
||||
self.nodes.insert(addr, node);
|
||||
addr
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn get_node(&mut self, addr: SocketAddr) -> &mut TestNode<P> {
|
||||
let node = self.nodes.get_mut(&addr).unwrap();
|
||||
DebugLogger::set_node(node.get_num());
|
||||
node
|
||||
}
|
||||
|
||||
pub fn simulate_next_message(&mut self) {
|
||||
if let Some((src, dst, data)) = self.messages.pop_front() {
|
||||
if let Some(node) = self.nodes.get_mut(&dst) {
|
||||
if node.socket().put_inbound(src, data) {
|
||||
DebugLogger::set_node(node.get_num());
|
||||
node.trigger_socket_event();
|
||||
DebugLogger::set_node(0);
|
||||
let sock = node.socket();
|
||||
let src = dst;
|
||||
while let Some((dst, data)) = sock.pop_outbound() {
|
||||
self.messages.push_back((src, dst, data));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
warn!("Message to unknown node {}", dst);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn simulate_all_messages(&mut self) {
|
||||
while !self.messages.is_empty() {
|
||||
self.simulate_next_message()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn trigger_node_housekeep(&mut self, addr: SocketAddr) {
|
||||
let node = self.nodes.get_mut(&addr).unwrap();
|
||||
DebugLogger::set_node(node.get_num());
|
||||
node.trigger_housekeep();
|
||||
DebugLogger::set_node(0);
|
||||
let sock = node.socket();
|
||||
while let Some((dst, data)) = sock.pop_outbound() {
|
||||
self.messages.push_back((addr, dst, data));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn trigger_housekeep(&mut self) {
|
||||
for (src, node) in &mut self.nodes {
|
||||
DebugLogger::set_node(node.get_num());
|
||||
node.trigger_housekeep();
|
||||
DebugLogger::set_node(0);
|
||||
let sock = node.socket();
|
||||
while let Some((dst, data)) = sock.pop_outbound() {
|
||||
self.messages.push_back((*src, dst, data));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_time(&mut self, time: Time) {
|
||||
MockTimeSource::set_time(time);
|
||||
}
|
||||
|
||||
pub fn simulate_time(&mut self, time: Time) {
|
||||
let mut t = MockTimeSource::now();
|
||||
while t < time {
|
||||
t += 1;
|
||||
self.set_time(t);
|
||||
self.trigger_housekeep();
|
||||
self.simulate_all_messages();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn connect(&mut self, src: SocketAddr, dst: SocketAddr) {
|
||||
let node = self.nodes.get_mut(&src).unwrap();
|
||||
DebugLogger::set_node(node.get_num());
|
||||
node.connect(dst).unwrap();
|
||||
DebugLogger::set_node(0);
|
||||
let sock = node.socket();
|
||||
while let Some((dst, data)) = sock.pop_outbound() {
|
||||
self.messages.push_back((src, dst, data));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_connected(&self, src: SocketAddr, dst: SocketAddr) -> bool {
|
||||
self.nodes.get(&src).unwrap().is_connected(&dst)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn node_addresses(&self) -> Vec<SocketAddr> {
|
||||
self.nodes.keys().copied().collect()
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn message_count(&self) -> usize {
|
||||
self.messages.len()
|
||||
}
|
||||
|
||||
pub fn put_payload(&mut self, addr: SocketAddr, data: Vec<u8>) {
|
||||
let node = self.nodes.get_mut(&addr).unwrap();
|
||||
node.device().put_inbound(data);
|
||||
DebugLogger::set_node(node.get_num());
|
||||
node.trigger_device_event();
|
||||
DebugLogger::set_node(0);
|
||||
let sock = node.socket();
|
||||
while let Some((dst, data)) = sock.pop_outbound() {
|
||||
self.messages.push_back((addr, dst, data));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn pop_payload(&mut self, node: SocketAddr) -> Option<Vec<u8>> {
|
||||
self.nodes.get_mut(&node).unwrap().device().pop_outbound()
|
||||
}
|
||||
|
||||
pub fn drop_message(&mut self) {
|
||||
self.messages.pop_front();
|
||||
}
|
||||
}
|
214
src/tests/mod.rs
214
src/tests/mod.rs
|
@ -1,218 +1,8 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2020 Dennis Schwerdel
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
mod common;
|
||||
mod nat;
|
||||
mod payload;
|
||||
mod peers;
|
||||
|
||||
use std::{
|
||||
collections::{HashMap, VecDeque},
|
||||
io::Write,
|
||||
net::SocketAddr,
|
||||
sync::{
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
Once
|
||||
}
|
||||
};
|
||||
|
||||
pub use super::{
|
||||
cloud::GenericCloud,
|
||||
config::{Config, CryptoConfig},
|
||||
device::{MockDevice, Type},
|
||||
net::MockSocket,
|
||||
payload::{Frame, Packet, Protocol},
|
||||
types::Range,
|
||||
util::{MockTimeSource, Time, TimeSource}
|
||||
};
|
||||
|
||||
|
||||
static INIT_LOGGER: Once = Once::new();
|
||||
|
||||
pub fn init_debug_logger() {
|
||||
INIT_LOGGER.call_once(|| {
|
||||
log::set_boxed_logger(Box::new(DebugLogger)).unwrap();
|
||||
log::set_max_level(log::LevelFilter::Debug);
|
||||
})
|
||||
}
|
||||
|
||||
static CURRENT_NODE: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
struct DebugLogger;
|
||||
|
||||
impl DebugLogger {
|
||||
pub fn set_node(node: usize) {
|
||||
CURRENT_NODE.store(node, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
impl log::Log for DebugLogger {
|
||||
#[inline]
|
||||
fn enabled(&self, _metadata: &log::Metadata) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn log(&self, record: &log::Record) {
|
||||
if self.enabled(record.metadata()) {
|
||||
eprintln!("Node {} - {} - {}", CURRENT_NODE.load(Ordering::SeqCst), record.level(), record.args());
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn flush(&self) {
|
||||
std::io::stderr().flush().expect("Failed to flush")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
type TestNode<P> = GenericCloud<MockDevice, P, MockSocket, MockTimeSource>;
|
||||
|
||||
pub struct Simulator<P: Protocol> {
|
||||
next_port: u16,
|
||||
nodes: HashMap<SocketAddr, TestNode<P>>,
|
||||
messages: VecDeque<(SocketAddr, SocketAddr, Vec<u8>)>
|
||||
}
|
||||
|
||||
pub type TapSimulator = Simulator<Frame>;
|
||||
#[allow(dead_code)]
|
||||
pub type TunSimulator = Simulator<Packet>;
|
||||
|
||||
|
||||
impl<P: Protocol> Simulator<P> {
|
||||
pub fn new() -> Self {
|
||||
init_debug_logger();
|
||||
MockTimeSource::set_time(0);
|
||||
Self { next_port: 1, nodes: HashMap::default(), messages: VecDeque::default() }
|
||||
}
|
||||
|
||||
pub fn add_node(&mut self, nat: bool, config: &Config) -> SocketAddr {
|
||||
let mut config = config.clone();
|
||||
MockSocket::set_nat(nat);
|
||||
config.listen = format!("[::]:{}", self.next_port);
|
||||
let addr = config.listen.parse::<SocketAddr>().unwrap();
|
||||
if config.crypto.password.is_none() && config.crypto.private_key.is_none() {
|
||||
config.crypto.password = Some("test123".to_string())
|
||||
}
|
||||
DebugLogger::set_node(self.next_port as usize);
|
||||
self.next_port += 1;
|
||||
let node = TestNode::new(&config, MockSocket::new(addr), MockDevice::new(), None, None);
|
||||
DebugLogger::set_node(0);
|
||||
self.nodes.insert(addr, node);
|
||||
addr
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn get_node(&mut self, addr: SocketAddr) -> &mut TestNode<P> {
|
||||
let node = self.nodes.get_mut(&addr).unwrap();
|
||||
DebugLogger::set_node(node.get_num());
|
||||
node
|
||||
}
|
||||
|
||||
pub fn simulate_next_message(&mut self) {
|
||||
if let Some((src, dst, data)) = self.messages.pop_front() {
|
||||
if let Some(node) = self.nodes.get_mut(&dst) {
|
||||
if node.socket().put_inbound(src, data) {
|
||||
DebugLogger::set_node(node.get_num());
|
||||
node.trigger_socket_event();
|
||||
DebugLogger::set_node(0);
|
||||
let sock = node.socket();
|
||||
let src = dst;
|
||||
while let Some((dst, data)) = sock.pop_outbound() {
|
||||
self.messages.push_back((src, dst, data));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
warn!("Message to unknown node {}", dst);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn simulate_all_messages(&mut self) {
|
||||
while !self.messages.is_empty() {
|
||||
self.simulate_next_message()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn trigger_node_housekeep(&mut self, addr: SocketAddr) {
|
||||
let node = self.nodes.get_mut(&addr).unwrap();
|
||||
DebugLogger::set_node(node.get_num());
|
||||
node.trigger_housekeep();
|
||||
DebugLogger::set_node(0);
|
||||
let sock = node.socket();
|
||||
while let Some((dst, data)) = sock.pop_outbound() {
|
||||
self.messages.push_back((addr, dst, data));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn trigger_housekeep(&mut self) {
|
||||
for (src, node) in &mut self.nodes {
|
||||
DebugLogger::set_node(node.get_num());
|
||||
node.trigger_housekeep();
|
||||
DebugLogger::set_node(0);
|
||||
let sock = node.socket();
|
||||
while let Some((dst, data)) = sock.pop_outbound() {
|
||||
self.messages.push_back((*src, dst, data));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_time(&mut self, time: Time) {
|
||||
MockTimeSource::set_time(time);
|
||||
}
|
||||
|
||||
pub fn simulate_time(&mut self, time: Time) {
|
||||
let mut t = MockTimeSource::now();
|
||||
while t < time {
|
||||
t += 1;
|
||||
self.set_time(t);
|
||||
self.trigger_housekeep();
|
||||
self.simulate_all_messages();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn connect(&mut self, src: SocketAddr, dst: SocketAddr) {
|
||||
let node = self.nodes.get_mut(&src).unwrap();
|
||||
DebugLogger::set_node(node.get_num());
|
||||
node.connect(dst).unwrap();
|
||||
DebugLogger::set_node(0);
|
||||
let sock = node.socket();
|
||||
while let Some((dst, data)) = sock.pop_outbound() {
|
||||
self.messages.push_back((src, dst, data));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_connected(&self, src: SocketAddr, dst: SocketAddr) -> bool {
|
||||
self.nodes.get(&src).unwrap().is_connected(&dst)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn node_addresses(&self) -> Vec<SocketAddr> {
|
||||
self.nodes.keys().copied().collect()
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn message_count(&self) -> usize {
|
||||
self.messages.len()
|
||||
}
|
||||
|
||||
pub fn put_payload(&mut self, addr: SocketAddr, data: Vec<u8>) {
|
||||
let node = self.nodes.get_mut(&addr).unwrap();
|
||||
node.device().put_inbound(data);
|
||||
DebugLogger::set_node(node.get_num());
|
||||
node.trigger_device_event();
|
||||
DebugLogger::set_node(0);
|
||||
let sock = node.socket();
|
||||
while let Some((dst, data)) = sock.pop_outbound() {
|
||||
self.messages.push_back((addr, dst, data));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn pop_payload(&mut self, node: SocketAddr) -> Option<Vec<u8>> {
|
||||
self.nodes.get_mut(&node).unwrap().device().pop_outbound()
|
||||
}
|
||||
|
||||
pub fn drop_message(&mut self) {
|
||||
self.messages.pop_front();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2020 Dennis Schwerdel
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
use super::*;
|
||||
use super::common::*;
|
||||
|
||||
#[test]
|
||||
fn connect_nat_2_peers() {
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2020 Dennis Schwerdel
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
use super::*;
|
||||
use super::common::*;
|
||||
|
||||
#[test]
|
||||
fn switch_delivers() {
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2020 Dennis Schwerdel
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
use super::*;
|
||||
use super::common::*;
|
||||
|
||||
#[test]
|
||||
fn direct_connect() {
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2018-2020 Dennis Schwerdel
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
use std::{
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2020 Dennis Schwerdel
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
use crate::{
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2020 Dennis Schwerdel
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
use std::process::Command;
|
||||
|
|
|
@ -1,3 +1,7 @@
|
|||
// VpnCloud - Peer-to-Peer VPN
|
||||
// Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
// This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
||||
use super::{
|
||||
net::{get_ip, mapped_addr, parse_listen, Socket},
|
||||
poll::{WaitImpl, WaitResult},
|
||||
|
|
|
@ -614,5 +614,5 @@ given.
|
|||
|
||||
== COPYRIGHT
|
||||
|
||||
Copyright (C) 2015-2020 Dennis Schwerdel
|
||||
Copyright (C) 2015-2021 Dennis Schwerdel
|
||||
This software is licensed under GPL-3 or newer (see LICENSE.md)
|
||||
|
|
Loading…
Reference in New Issue