Compare commits

...

243 Commits

Author SHA1 Message Date
Dennis Schwerdel bef99162fe Remove github package workflow 2024-03-21 14:15:55 +01:00
Dennis Schwerdel 24c48e2ef2 Add sign 2024-03-21 14:15:00 +01:00
Dennis Schwerdel 7e55ec5df6 Use mask & cross 2024-03-19 23:15:04 +01:00
Dennis Schwerdel 18e4a22210 Update deps, remove devcontainer, fix lints 2024-03-18 22:08:21 +01:00
Dennis Schwerdel 06f3d3c761 Fix interface address get/set 2023-10-09 01:31:43 +02:00
Dennis Schwerdel 5eeb125d74 Dev container 2023-10-07 01:16:55 +02:00
Dennis Schwerdel ca220ded0c Clippy 2023-10-07 01:12:47 +02:00
Dennis Schwerdel 2505679021 Remove coverage 2023-10-07 01:05:46 +02:00
Dennis Schwerdel 358183ef12 Fix #350 2023-10-07 00:59:50 +02:00
Dennis Schwerdel 28b1c76d70 Update dependencies 2023-10-07 00:56:32 +02:00
Dennis Schwerdel 5c361d08ab Fix static build 2021-12-23 21:55:43 +01:00
Dennis Schwerdel 16d5d47f01 Release v2.3.0 2021-12-23 21:33:50 +01:00
Dennis Schwerdel 50a6c01e93 Fix repeating broadcasts 2021-12-20 08:50:12 +01:00
Dennis Schwerdel 2dc774196e Update audit workflow 2021-12-20 08:25:26 +01:00
Dennis Schwerdel 79916104ba Make clippy happy 2021-12-19 13:54:09 +01:00
Dennis Schwerdel 798964030f Update tungstenite 2021-12-19 12:51:52 +01:00
Dennis Schwerdel c7c1ebc11b Add armv5te to automatic builds 2021-12-19 12:40:43 +01:00
Dennis Schwerdel 4896a964ea Merge branch 'master' of github.com:dswd/vpncloud 2021-12-19 11:34:52 +01:00
dswd 59920ff627
Merge pull request #274 from xek/armel
Create armel build targets for cross compilation
2021-12-19 11:32:23 +01:00
dswd 665b4d505f
Merge pull request #273 from dswd/dependabot/cargo/serde-1.0.132
Bump serde from 1.0.130 to 1.0.132
2021-12-19 11:31:15 +01:00
dswd 6c5065c267
Merge pull request #272 from dswd/dependabot/cargo/libc-0.2.112
Bump libc from 0.2.107 to 0.2.112
2021-12-19 11:31:05 +01:00
dswd 8d6c2b955e
Merge pull request #271 from dswd/dependabot/cargo/serde_yaml-0.8.23
Bump serde_yaml from 0.8.21 to 0.8.23
2021-12-19 11:30:56 +01:00
Grzegorz Grasza c61abbdb34 Create armel build targets for cross compilation
This adds armv5te-unknown-linux-gnueabi and armv5te-unknown-linux-musleabi
targets in the builder/build.sh script.
2021-12-17 12:11:32 +01:00
dependabot[bot] cd5c58239b
Bump serde from 1.0.130 to 1.0.132
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.130 to 1.0.132.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.130...v1.0.132)

---
updated-dependencies:
- dependency-name: serde
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-12-17 09:02:27 +00:00
dependabot[bot] e52c28794e
Bump libc from 0.2.107 to 0.2.112
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.107 to 0.2.112.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.107...0.2.112)

---
updated-dependencies:
- dependency-name: libc
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-12-14 09:02:21 +00:00
dependabot[bot] e70a0412f9
Bump serde_yaml from 0.8.21 to 0.8.23
Bumps [serde_yaml](https://github.com/dtolnay/serde-yaml) from 0.8.21 to 0.8.23.
- [Release notes](https://github.com/dtolnay/serde-yaml/releases)
- [Commits](https://github.com/dtolnay/serde-yaml/compare/0.8.21...0.8.23)

---
updated-dependencies:
- dependency-name: serde_yaml
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-12-13 09:02:25 +00:00
dswd 0d19bb04e8
Merge pull request #259 from dswd/dependabot/cargo/smallvec-1.7.0
Bump smallvec from 1.6.1 to 1.7.0
2021-11-09 10:42:12 +01:00
dswd bb97bfd2c5
Merge pull request #258 from dswd/dependabot/cargo/structopt-0.3.25
Bump structopt from 0.3.22 to 0.3.25
2021-11-09 10:42:03 +01:00
dependabot[bot] 87446af0b2
Bump smallvec from 1.6.1 to 1.7.0
Bumps [smallvec](https://github.com/servo/rust-smallvec) from 1.6.1 to 1.7.0.
- [Release notes](https://github.com/servo/rust-smallvec/releases)
- [Commits](https://github.com/servo/rust-smallvec/compare/v1.6.1...v1.7.0)

---
updated-dependencies:
- dependency-name: smallvec
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-11-09 09:35:15 +00:00
dswd 85fc272ad4
Merge pull request #256 from dswd/dependabot/cargo/dialoguer-0.9.0
Bump dialoguer from 0.8.0 to 0.9.0
2021-11-09 10:34:01 +01:00
dswd 1368ee50e5
Merge pull request #257 from dswd/dependabot/cargo/privdrop-0.5.1
Bump privdrop from 0.5.0 to 0.5.1
2021-11-09 10:33:53 +01:00
dependabot[bot] 45216f7ef2
Bump structopt from 0.3.22 to 0.3.25
Bumps [structopt](https://github.com/TeXitoi/structopt) from 0.3.22 to 0.3.25.
- [Release notes](https://github.com/TeXitoi/structopt/releases)
- [Changelog](https://github.com/TeXitoi/structopt/blob/master/CHANGELOG.md)
- [Commits](https://github.com/TeXitoi/structopt/compare/v0.3.22...v0.3.25)

---
updated-dependencies:
- dependency-name: structopt
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-11-09 09:30:36 +00:00
dependabot[bot] d71225b88d
Bump privdrop from 0.5.0 to 0.5.1
Bumps [privdrop](https://github.com/jedisct1/rust-privdrop) from 0.5.0 to 0.5.1.
- [Release notes](https://github.com/jedisct1/rust-privdrop/releases)
- [Commits](https://github.com/jedisct1/rust-privdrop/compare/0.5.0...0.5.1)

---
updated-dependencies:
- dependency-name: privdrop
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-11-09 09:30:32 +00:00
dependabot[bot] bd50eaec77
Bump dialoguer from 0.8.0 to 0.9.0
Bumps [dialoguer](https://github.com/mitsuhiko/dialoguer) from 0.8.0 to 0.9.0.
- [Release notes](https://github.com/mitsuhiko/dialoguer/releases)
- [Changelog](https://github.com/mitsuhiko/dialoguer/blob/master/CHANGELOG.md)
- [Commits](https://github.com/mitsuhiko/dialoguer/compare/0.8.0...v0.9.0)

---
updated-dependencies:
- dependency-name: dialoguer
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-11-09 09:30:28 +00:00
dswd 95dabab017
Merge pull request #239 from dswd/dependabot/cargo/serde_yaml-0.8.21
Bump serde_yaml from 0.8.18 to 0.8.21
2021-11-09 10:30:00 +01:00
dswd e4956d209b
Merge pull request #235 from dswd/dependabot/cargo/serde-1.0.130
Bump serde from 1.0.127 to 1.0.130
2021-11-09 10:29:52 +01:00
dswd 46f083ed68
Merge pull request #243 from dswd/dependabot/cargo/thiserror-1.0.30
Bump thiserror from 1.0.26 to 1.0.30
2021-11-09 10:29:43 +01:00
dswd 88d34e2fcd
Merge pull request #254 from dswd/dependabot/cargo/libc-0.2.107
Bump libc from 0.2.99 to 0.2.107
2021-11-09 10:29:33 +01:00
dependabot[bot] 4cbbc21a76
Bump libc from 0.2.99 to 0.2.107
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.99 to 0.2.107.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.99...0.2.107)

---
updated-dependencies:
- dependency-name: libc
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-11-08 09:01:31 +00:00
dependabot[bot] 4c9df625df
Bump thiserror from 1.0.26 to 1.0.30
Bumps [thiserror](https://github.com/dtolnay/thiserror) from 1.0.26 to 1.0.30.
- [Release notes](https://github.com/dtolnay/thiserror/releases)
- [Commits](https://github.com/dtolnay/thiserror/compare/1.0.26...1.0.30)

---
updated-dependencies:
- dependency-name: thiserror
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-10-11 09:01:37 +00:00
dependabot[bot] 7cbbababce
Bump serde_yaml from 0.8.18 to 0.8.21
Bumps [serde_yaml](https://github.com/dtolnay/serde-yaml) from 0.8.18 to 0.8.21.
- [Release notes](https://github.com/dtolnay/serde-yaml/releases)
- [Commits](https://github.com/dtolnay/serde-yaml/compare/0.8.18...0.8.21)

---
updated-dependencies:
- dependency-name: serde_yaml
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-09-13 09:02:00 +00:00
dependabot[bot] 1ddb18d63b
Bump serde from 1.0.127 to 1.0.130
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.127 to 1.0.130.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.127...v1.0.130)

---
updated-dependencies:
- dependency-name: serde
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-08-30 09:02:14 +00:00
dswd b584eb7163
Merge pull request #219 from dswd/dependabot/cargo/libc-0.2.99
Bump libc from 0.2.98 to 0.2.99
2021-08-20 18:37:00 +02:00
dswd 115e42b553
Merge pull request #217 from dswd/dependabot/cargo/criterion-0.3.5
Bump criterion from 0.3.4 to 0.3.5
2021-08-20 18:36:08 +02:00
dswd dd529f15ff
Merge pull request #218 from dswd/dependabot/cargo/serde-1.0.127
Bump serde from 1.0.126 to 1.0.127
2021-08-20 18:36:00 +02:00
dswd 062868dfd0
Merge pull request #224 from dswd/dependabot/cargo/serde_yaml-0.8.18
Bump serde_yaml from 0.8.17 to 0.8.18
2021-08-20 18:35:52 +02:00
dependabot[bot] 2810eebca2
Bump serde_yaml from 0.8.17 to 0.8.18
Bumps [serde_yaml](https://github.com/dtolnay/serde-yaml) from 0.8.17 to 0.8.18.
- [Release notes](https://github.com/dtolnay/serde-yaml/releases)
- [Commits](https://github.com/dtolnay/serde-yaml/compare/0.8.17...0.8.18)

---
updated-dependencies:
- dependency-name: serde_yaml
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-08-18 09:01:24 +00:00
dependabot[bot] a69b6e94cf
Bump libc from 0.2.98 to 0.2.99
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.98 to 0.2.99.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.98...0.2.99)

---
updated-dependencies:
- dependency-name: libc
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-08-10 09:01:42 +00:00
dependabot[bot] d70ff828bc
Bump serde from 1.0.126 to 1.0.127
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.126 to 1.0.127.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.126...v1.0.127)

---
updated-dependencies:
- dependency-name: serde
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-08-02 09:01:36 +00:00
dependabot[bot] 96cf585ca6
Bump criterion from 0.3.4 to 0.3.5
Bumps [criterion](https://github.com/bheisler/criterion.rs) from 0.3.4 to 0.3.5.
- [Release notes](https://github.com/bheisler/criterion.rs/releases)
- [Changelog](https://github.com/bheisler/criterion.rs/blob/master/CHANGELOG.md)
- [Commits](https://github.com/bheisler/criterion.rs/compare/0.3.4...0.3.5)

---
updated-dependencies:
- dependency-name: criterion
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-07-27 09:01:39 +00:00
dswd ba0a903774
Merge pull request #211 from dswd/dependabot/cargo/libc-0.2.98
Bump libc from 0.2.97 to 0.2.98
2021-07-18 19:06:11 +02:00
dswd 7213cc055d
Merge pull request #214 from dswd/dependabot/cargo/tungstenite-0.14.0
Bump tungstenite from 0.13.0 to 0.14.0
2021-07-18 19:06:02 +02:00
dswd 8bd1479904
Merge pull request #216 from hg/wizard-msg
Fix wrong service control command in wizard message
2021-07-18 19:05:45 +02:00
Kirill Isakov 2adbc07cc3
Fix wrong service control command in wizard message 2021-07-18 20:38:38 +06:00
dependabot[bot] 4868e8064c
Bump tungstenite from 0.13.0 to 0.14.0
Bumps [tungstenite](https://github.com/snapview/tungstenite-rs) from 0.13.0 to 0.14.0.
- [Release notes](https://github.com/snapview/tungstenite-rs/releases)
- [Changelog](https://github.com/snapview/tungstenite-rs/blob/master/CHANGELOG.md)
- [Commits](https://github.com/snapview/tungstenite-rs/compare/v0.13.0...v0.14.0)

---
updated-dependencies:
- dependency-name: tungstenite
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-07-12 09:01:15 +00:00
dependabot[bot] 671454f59c
Bump libc from 0.2.97 to 0.2.98
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.97 to 0.2.98.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.97...0.2.98)

---
updated-dependencies:
- dependency-name: libc
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-07-08 09:01:22 +00:00
dswd 6e5f71b116
Merge pull request #207 from dswd/dependabot/cargo/structopt-0.3.22
Bump structopt from 0.3.21 to 0.3.22
2021-07-06 23:53:58 +02:00
dswd 5e5522d6bd
Merge pull request #208 from dswd/dependabot/cargo/thiserror-1.0.26
Bump thiserror from 1.0.25 to 1.0.26
2021-07-06 23:53:51 +02:00
dependabot[bot] 883fae862f
Bump thiserror from 1.0.25 to 1.0.26
Bumps [thiserror](https://github.com/dtolnay/thiserror) from 1.0.25 to 1.0.26.
- [Release notes](https://github.com/dtolnay/thiserror/releases)
- [Commits](https://github.com/dtolnay/thiserror/compare/1.0.25...1.0.26)

---
updated-dependencies:
- dependency-name: thiserror
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-07-05 09:01:34 +00:00
dependabot[bot] 9601aeffee
Bump structopt from 0.3.21 to 0.3.22
Bumps [structopt](https://github.com/TeXitoi/structopt) from 0.3.21 to 0.3.22.
- [Release notes](https://github.com/TeXitoi/structopt/releases)
- [Changelog](https://github.com/TeXitoi/structopt/blob/master/CHANGELOG.md)
- [Commits](https://github.com/TeXitoi/structopt/compare/v0.3.21...v0.3.22)

---
updated-dependencies:
- dependency-name: structopt
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-07-05 09:01:28 +00:00
dswd 7209e311c9
Merge pull request #204 from dswd/dependabot/cargo/rand-0.8.4
Bump rand from 0.8.3 to 0.8.4
2021-06-18 08:46:14 +02:00
dependabot[bot] 1e9eb41ea6
Bump rand from 0.8.3 to 0.8.4
Bumps [rand](https://github.com/rust-random/rand) from 0.8.3 to 0.8.4.
- [Release notes](https://github.com/rust-random/rand/releases)
- [Changelog](https://github.com/rust-random/rand/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-random/rand/compare/0.8.3...0.8.4)

---
updated-dependencies:
- dependency-name: rand
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-06-16 05:11:43 +00:00
dswd 06d29c8e3c
Merge pull request #203 from dswd/dependabot/cargo/libc-0.2.97
Bump libc from 0.2.96 to 0.2.97
2021-06-15 09:18:05 +02:00
dependabot[bot] 1ac20db0b3
Bump libc from 0.2.96 to 0.2.97
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.96 to 0.2.97.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.96...0.2.97)

---
updated-dependencies:
- dependency-name: libc
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-06-14 05:44:28 +00:00
dswd ba15bcfabf
Merge pull request #200 from dswd/dependabot/cargo/libc-0.2.96
Bump libc from 0.2.95 to 0.2.96
2021-06-11 15:25:42 +02:00
dependabot[bot] 129d0e5e93
Bump libc from 0.2.95 to 0.2.96
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.95 to 0.2.96.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.95...0.2.96)

---
updated-dependencies:
- dependency-name: libc
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-06-09 05:04:04 +00:00
Dennis Schwerdel 10ee616d89 Changelog 2021-05-27 17:01:34 +02:00
Dennis Schwerdel ad75704f7b Fix listen with IPv4 error (#198) 2021-05-27 08:16:38 +02:00
dswd 4d8286c54c
Merge pull request #196 from dswd/dependabot/cargo/thiserror-1.0.25
Bump thiserror from 1.0.24 to 1.0.25
2021-05-26 21:35:33 +02:00
dswd 00bf732be9
Merge pull request #197 from dswd/dependabot/cargo/libc-0.2.95
Bump libc from 0.2.94 to 0.2.95
2021-05-26 21:35:27 +02:00
dependabot[bot] 817d060441
Bump libc from 0.2.94 to 0.2.95
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.94 to 0.2.95.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.94...0.2.95)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-26 05:03:08 +00:00
dependabot[bot] cc105daac6
Bump thiserror from 1.0.24 to 1.0.25
Bumps [thiserror](https://github.com/dtolnay/thiserror) from 1.0.24 to 1.0.25.
- [Release notes](https://github.com/dtolnay/thiserror/releases)
- [Commits](https://github.com/dtolnay/thiserror/compare/1.0.24...1.0.25)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-24 05:30:00 +00:00
dswd 36195cb582
Merge pull request #192 from dswd/dependabot/cargo/serde-1.0.126
Bump serde from 1.0.125 to 1.0.126
2021-05-13 15:00:11 +02:00
dependabot[bot] f77ac6d6f4
Bump serde from 1.0.125 to 1.0.126
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.125 to 1.0.126.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.125...v1.0.126)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-13 05:16:36 +00:00
dswd 8fe0815acd
Merge pull request #191 from dswd/dependabot/cargo/url-2.2.2
Bump url from 2.2.1 to 2.2.2
2021-05-10 10:14:05 +02:00
dependabot[bot] 0119820495
Bump url from 2.2.1 to 2.2.2
Bumps [url](https://github.com/servo/rust-url) from 2.2.1 to 2.2.2.
- [Release notes](https://github.com/servo/rust-url/releases)
- [Commits](https://github.com/servo/rust-url/compare/v2.2.1...v2.2.2)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-10 05:30:48 +00:00
dswd e77cb6ef0f
Merge pull request #188 from dswd/dependabot/cargo/libc-0.2.94
Bump libc from 0.2.93 to 0.2.94
2021-04-27 13:01:00 +02:00
dependabot[bot] 213faa5649
Bump libc from 0.2.93 to 0.2.94
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.93 to 0.2.94.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.93...0.2.94)

Signed-off-by: dependabot[bot] <support@github.com>
2021-04-27 05:18:48 +00:00
dswd 396351b61c
Update config.yml 2021-04-18 20:33:32 +02:00
dswd 41bcb46579
Create issue_template.md 2021-04-18 20:32:18 +02:00
dswd b0d73c44ed
Update config.yml 2021-04-18 19:41:54 +02:00
dswd ea53a4aad5
Create config.yml 2021-04-18 19:40:29 +02:00
dswd 25e2f327e9 Update issue templates 2021-04-18 19:36:56 +02:00
Dennis Schwerdel 37aebf64c3 Remove time in favor of chrono 2021-04-12 19:47:17 +02:00
Dennis Schwerdel 8d81a0117f Update changelog 2021-04-12 19:30:57 +02:00
Dennis Schwerdel 8c55e6c076 Finish advertise address & exchange own addresses 2021-04-09 22:01:35 +02:00
Dennis Schwerdel 7427be31c8 Merge branch 'master' of github.com:dswd/vpncloud 2021-04-09 20:31:16 +02:00
Dennis Schwerdel 5609a61ddb Add performance for 2.2.0 2021-04-09 20:31:13 +02:00
Jeffrey Schiller 0f9a0d8f91
Add ability to configure “own” addresses (#185)
* Add ability to configure “own” addresses

This configuration option permits the declaration of external or public
addresses instead of attempting to learn them from port forwarding or
interfaces. This is useful in situations where it isn’t possible to
accurately obtain the correct external addresses that peers should use.

* Update args and use better parse listen address

Add the --advertise_addresses control argument to accompany the new
configuration option. Also parse the listen address/port to extract the
port to advertise with advertise_addresses instead of assuming it is
just a port.
2021-04-09 20:30:16 +02:00
dswd 7a55529cb9
Merge pull request #184 from dswd/dependabot/cargo/libc-0.2.93
Bump libc from 0.2.92 to 0.2.93
2021-04-07 18:56:38 +02:00
dependabot[bot] eef6e528e2
Bump libc from 0.2.92 to 0.2.93
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.92 to 0.2.93.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.92...0.2.93)

Signed-off-by: dependabot[bot] <support@github.com>
2021-04-07 05:18:23 +00:00
Dennis Schwerdel 4fb92a36a6 Prepare for release 2021-04-06 12:28:31 +02:00
Dennis Schwerdel 665b190257 Fix permissions 2021-04-06 00:18:33 +02:00
Dennis Schwerdel ff75845dfb Fix rpm build 2021-04-05 22:50:35 +02:00
Dennis Schwerdel 97e168c856 Fix check action 2021-04-05 17:06:19 +00:00
Dennis Schwerdel 3b96380b42 Update deps 2021-04-05 17:01:40 +00:00
Dennis Schwerdel 6d4591f685 Install .target file 2021-04-05 16:55:09 +00:00
dswd 41e8ecd962
Merge pull request #182 from mnhauke/master
systemd: add file vpncloud.target
2021-04-05 18:51:21 +02:00
Dennis Schwerdel ea3b2e22a6 Merge branch 'master' of github.com:dswd/vpncloud 2021-04-05 16:50:22 +00:00
Martin Hauke 151ca445c3 systemd: add file vpncloud.target
Add file vpncloud.target, which allows you to stop or restart all
instances.
2021-04-04 22:02:39 +02:00
dswd b745735af8
Merge pull request #181 from dswd/dependabot/cargo/libc-0.2.92
Bump libc from 0.2.91 to 0.2.92
2021-04-02 10:58:28 +02:00
dependabot[bot] 07d65df6ee
Bump libc from 0.2.91 to 0.2.92
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.91 to 0.2.92.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.91...0.2.92)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-31 05:05:49 +00:00
Dennis Schwerdel d7d06941e5 Test for broken time crate 2021-03-26 08:16:23 +01:00
Dennis Schwerdel 62def2de17 Merge branch 'master' of github.com:dswd/vpncloud 2021-03-23 08:05:39 +00:00
dswd 8df6214fd7
Merge pull request #178 from dswd/dependabot/cargo/libc-0.2.91
Bump libc from 0.2.88 to 0.2.91
2021-03-23 09:04:25 +01:00
dswd 940707333c
Merge pull request #179 from dswd/dependabot/cargo/serde-1.0.125
Bump serde from 1.0.124 to 1.0.125
2021-03-23 09:03:38 +01:00
dependabot[bot] 8675fdee87
Bump serde from 1.0.124 to 1.0.125
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.124 to 1.0.125.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.124...v1.0.125)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-23 05:16:35 +00:00
dependabot[bot] 5053bfa559
Bump libc from 0.2.88 to 0.2.91
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.88 to 0.2.91.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.88...0.2.91)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-23 05:16:30 +00:00
dswd bcc029afea
Merge pull request #172 from dswd/dependabot/cargo/dialoguer-0.8.0
Bump dialoguer from 0.7.1 to 0.8.0
2021-03-15 08:43:19 +01:00
dswd 35ac0339e7
Merge pull request #171 from dswd/dependabot/cargo/byteorder-1.4.3
Bump byteorder from 1.4.2 to 1.4.3
2021-03-15 08:43:09 +01:00
dependabot[bot] 186f3fc215
Bump dialoguer from 0.7.1 to 0.8.0
Bumps [dialoguer](https://github.com/mitsuhiko/dialoguer) from 0.7.1 to 0.8.0.
- [Release notes](https://github.com/mitsuhiko/dialoguer/releases)
- [Changelog](https://github.com/mitsuhiko/dialoguer/blob/master/CHANGELOG.md)
- [Commits](https://github.com/mitsuhiko/dialoguer/compare/0.7.1...0.8.0)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-15 05:27:35 +00:00
dependabot[bot] e643217671
Bump byteorder from 1.4.2 to 1.4.3
Bumps [byteorder](https://github.com/BurntSushi/byteorder) from 1.4.2 to 1.4.3.
- [Release notes](https://github.com/BurntSushi/byteorder/releases)
- [Changelog](https://github.com/BurntSushi/byteorder/blob/master/CHANGELOG.md)
- [Commits](https://github.com/BurntSushi/byteorder/compare/1.4.2...1.4.3)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-11 05:17:50 +00:00
dswd 1e53e98c58
Merge pull request #170 from dswd/dependabot/cargo/serde-1.0.124
Bump serde from 1.0.123 to 1.0.124
2021-03-08 22:11:56 +01:00
dswd dd4b38e274
Merge pull request #169 from dswd/dependabot/cargo/libc-0.2.88
Bump libc from 0.2.87 to 0.2.88
2021-03-08 22:11:35 +01:00
dependabot[bot] a427ce70bd
Bump serde from 1.0.123 to 1.0.124
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.123 to 1.0.124.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.123...v1.0.124)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-08 05:29:10 +00:00
dependabot[bot] 2b79496e2c
Bump libc from 0.2.87 to 0.2.88
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.87 to 0.2.88.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.87...0.2.88)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-08 05:29:07 +00:00
dswd 2f69450af7
Merge pull request #168 from dswd/dependabot/cargo/libc-0.2.87
Bump libc from 0.2.86 to 0.2.87
2021-03-07 18:09:14 +01:00
dependabot[bot] c8192928dc
Bump libc from 0.2.86 to 0.2.87
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.86 to 0.2.87.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.86...0.2.87)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-03 05:06:20 +00:00
Dennis Schwerdel 493dcad170 Reformat dev container 2021-03-01 23:57:51 +00:00
Dennis Schwerdel f11c0efb8b Improve build&package 2021-02-22 16:19:19 +01:00
dswd 5176c32cc2
Merge pull request #163 from dswd/whitesource/configure
Configure WhiteSource Bolt for GitHub
2021-02-20 01:48:31 +01:00
whitesource-bolt-for-github[bot] 8c1c04ddf3
Add .whitesource configuration file 2021-02-20 00:46:37 +00:00
dswd e47d7fb4c7
Merge pull request #161 from dswd/dependabot/cargo/thiserror-1.0.24
Bump thiserror from 1.0.23 to 1.0.24
2021-02-19 11:30:04 +01:00
dswd 0ebc7fc7b6
Merge pull request #162 from dswd/dependabot/cargo/url-2.2.1
Bump url from 2.2.0 to 2.2.1
2021-02-19 11:29:57 +01:00
dependabot[bot] 137a9d18e2
Bump url from 2.2.0 to 2.2.1
Bumps [url](https://github.com/servo/rust-url) from 2.2.0 to 2.2.1.
- [Release notes](https://github.com/servo/rust-url/releases)
- [Commits](https://github.com/servo/rust-url/compare/v2.2.0...v2.2.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-19 05:20:08 +00:00
dependabot[bot] 34ecf9f9e9
Bump thiserror from 1.0.23 to 1.0.24
Bumps [thiserror](https://github.com/dtolnay/thiserror) from 1.0.23 to 1.0.24.
- [Release notes](https://github.com/dtolnay/thiserror/releases)
- [Commits](https://github.com/dtolnay/thiserror/compare/1.0.23...1.0.24)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-19 05:20:04 +00:00
Dennis Schwerdel 3da0d27eb7 Up deps 2021-02-17 21:18:36 +01:00
Dennis Schwerdel 8e49311fef Container for asciinema recorder 2021-02-16 22:41:14 +01:00
Dennis Schwerdel c63b2d1cd5 Organize contrib folder 2021-02-16 22:37:18 +01:00
dswd ac95f34402
Merge pull request #158 from dswd/dependabot/cargo/serde_yaml-0.8.17
Bump serde_yaml from 0.8.16 to 0.8.17
2021-02-15 08:19:38 +01:00
Dennis Schwerdel 4950753548 Static builds that can install themselves 2021-02-14 13:27:26 +01:00
Dennis Schwerdel c4ff0ed198 Add config wizard 2021-02-14 00:09:11 +01:00
dependabot[bot] 6b88ac5733
Bump serde_yaml from 0.8.16 to 0.8.17
Bumps [serde_yaml](https://github.com/dtolnay/serde-yaml) from 0.8.16 to 0.8.17.
- [Release notes](https://github.com/dtolnay/serde-yaml/releases)
- [Commits](https://github.com/dtolnay/serde-yaml/compare/0.8.16...0.8.17)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-11 05:20:09 +00:00
Dennis Schwerdel ad2e2014eb Change description 2021-02-09 16:23:34 +01:00
dswd 522d7d3f9c
Merge pull request #157 from dswd/dependabot/cargo/libc-0.2.86
Bump libc from 0.2.85 to 0.2.86
2021-02-09 16:21:10 +01:00
dswd ee618ba042
Merge pull request #156 from dswd/dependabot/cargo/tungstenite-0.13.0
Bump tungstenite from 0.12.0 to 0.13.0
2021-02-09 16:20:59 +01:00
dependabot[bot] 61b66fa71c
Bump tungstenite from 0.12.0 to 0.13.0
Bumps [tungstenite](https://github.com/snapview/tungstenite-rs) from 0.12.0 to 0.13.0.
- [Release notes](https://github.com/snapview/tungstenite-rs/releases)
- [Changelog](https://github.com/snapview/tungstenite-rs/blob/master/CHANGELOG.md)
- [Commits](https://github.com/snapview/tungstenite-rs/compare/v0.12.0...v0.13.0)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-09 07:24:05 +00:00
dependabot[bot] 506c0656ef
Bump libc from 0.2.85 to 0.2.86
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.85 to 0.2.86.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.85...0.2.86)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-09 07:23:12 +00:00
Dennis Schwerdel 2955a80af4 More benchmarking 2021-02-08 17:30:58 +01:00
Dennis Schwerdel 38c3ba1177 Add service for ws proxy 2021-02-08 15:13:58 +01:00
Dennis Schwerdel 0cffea7017 Change example config file 2021-02-08 10:11:35 +01:00
Dennis Schwerdel 7abeea1f95 Update copyright 2021-02-08 10:11:20 +01:00
Dennis Schwerdel 29630ab763 Update benches 2021-02-08 10:06:47 +01:00
Dennis Schwerdel ecebd2aab8 Some updates 2021-02-07 19:42:23 +01:00
Dennis Schwerdel d9a2ee28cc Release v2.1.0 2021-02-06 13:27:19 +01:00
Dennis Schwerdel 5236adf7b3 Fix some lints 2021-02-06 13:09:11 +01:00
Dennis Schwerdel 13688edd75 Prepare release 2021-02-05 18:27:48 +01:00
Dennis Schwerdel ed260d9a98 Merge branch 'master' of github.com:dswd/vpncloud 2021-02-04 23:43:16 +01:00
Dennis Schwerdel d154f85ecd Changelog 2021-02-04 23:42:51 +01:00
Dennis Schwerdel 65eef143cd Small improvements 2021-02-04 23:38:08 +01:00
Dennis Schwerdel 791ecfb0fe Remove tls support on client 2021-02-04 22:12:20 +01:00
Dennis Schwerdel e9122743e9 Feature gate websockets 2021-02-04 21:42:38 +01:00
Dennis Schwerdel bd0d102358 Add configurable WS port 2021-02-04 21:19:05 +01:00
Dennis Schwerdel a113b3ba22 Remove unused imports 2021-02-03 22:46:53 +01:00
Dennis Schwerdel f0d9ad2ccd Merge branch 'master' into wsproxy 2021-02-03 22:44:31 +01:00
Dennis Schwerdel e3fa631ed9 Working example 2021-02-03 22:03:42 +01:00
dswd 4c934ea028
Merge pull request #150 from dswd/dependabot/cargo/libc-0.2.85
Bump libc from 0.2.84 to 0.2.85
2021-02-03 18:00:24 +01:00
dswd 03ec09d27c
Merge pull request #151 from dswd/dependabot/cargo/serde_yaml-0.8.16
Bump serde_yaml from 0.8.15 to 0.8.16
2021-02-03 18:00:14 +01:00
dependabot[bot] 221d4ed490
Bump serde_yaml from 0.8.15 to 0.8.16
Bumps [serde_yaml](https://github.com/dtolnay/serde-yaml) from 0.8.15 to 0.8.16.
- [Release notes](https://github.com/dtolnay/serde-yaml/releases)
- [Commits](https://github.com/dtolnay/serde-yaml/compare/0.8.15...0.8.16)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-03 05:13:41 +00:00
dependabot[bot] f637af0faa
Bump libc from 0.2.84 to 0.2.85
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.84 to 0.2.85.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.84...0.2.85)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-03 05:13:39 +00:00
dswd 1e11e15ea6
Merge pull request #149 from dswd/dependabot/cargo/ring-0.16.20
Bump ring from 0.16.19 to 0.16.20
2021-02-02 07:55:14 +01:00
dependabot[bot] 79c4f4ef9f
Bump ring from 0.16.19 to 0.16.20
Bumps [ring](https://github.com/briansmith/ring) from 0.16.19 to 0.16.20.
- [Release notes](https://github.com/briansmith/ring/releases)
- [Commits](https://github.com/briansmith/ring/commits)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-02 05:21:33 +00:00
dswd 0c3cbcf390
Merge pull request #148 from dswd/dependabot/cargo/libc-0.2.84
Bump libc from 0.2.83 to 0.2.84
2021-01-30 16:44:11 +01:00
dependabot[bot] 7f135fbf24
Bump libc from 0.2.83 to 0.2.84
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.83 to 0.2.84.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/commits)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-29 18:29:03 +00:00
Dennis Schwerdel cbd38ed712 Document hot paths 2021-01-28 23:19:20 +01:00
Dennis Schwerdel ca7df77532 Use criterion for benchmarking 2021-01-28 22:54:29 +01:00
dswd 238b8a22f1
Merge pull request #146 from dswd/dependabot/cargo/log-0.4.14
Bump log from 0.4.13 to 0.4.14
2021-01-28 17:56:44 +01:00
dswd 556126572c
Merge pull request #147 from dswd/dependabot/cargo/libc-0.2.83
Bump libc from 0.2.82 to 0.2.83
2021-01-28 17:56:28 +01:00
dependabot[bot] 1b79a9f115
Bump libc from 0.2.82 to 0.2.83
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.82 to 0.2.83.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.82...0.2.83)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-28 05:24:26 +00:00
dependabot[bot] a2c179d4fb
Bump log from 0.4.13 to 0.4.14
Bumps [log](https://github.com/rust-lang/log) from 0.4.13 to 0.4.14.
- [Release notes](https://github.com/rust-lang/log/releases)
- [Changelog](https://github.com/rust-lang/log/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/log/compare/0.4.13...0.4.14)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-27 05:28:44 +00:00
Dennis Schwerdel e150443891 Deps 2021-01-26 18:30:31 +01:00
dswd cce43cbf49
Merge pull request #141 from dswd/dependabot/cargo/serde-1.0.122
Bump serde from 1.0.121 to 1.0.122
2021-01-25 20:55:49 +01:00
dswd b855789584
Merge pull request #143 from dswd/dependabot/cargo/serde_derive-1.0.122
Bump serde_derive from 1.0.121 to 1.0.122
2021-01-25 20:55:31 +01:00
dependabot[bot] f1d83fe1d4
Bump serde_derive from 1.0.121 to 1.0.122
Bumps [serde_derive](https://github.com/serde-rs/serde) from 1.0.121 to 1.0.122.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.121...v1.0.122)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-25 05:39:35 +00:00
dependabot[bot] 6e5dfc1b81
Bump serde from 1.0.121 to 1.0.122
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.121 to 1.0.122.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.121...v1.0.122)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-25 05:39:29 +00:00
Dennis Schwerdel 13f7d02086 Up deps 2021-01-24 19:26:53 +01:00
Dennis Schwerdel cd619d3980 Merge branch 'hooks' 2021-01-24 19:25:57 +01:00
Dennis Schwerdel 2a8ea5087b Changelog entry 2021-01-24 19:25:34 +01:00
Dennis Schwerdel f95fb17dd4 rename to hook 2021-01-24 19:24:40 +01:00
Dennis Schwerdel b6f4460f29 Fix tests 2021-01-24 17:47:02 +01:00
Dennis Schwerdel 8c4d86a101 node_id formatting 2021-01-23 21:18:25 +01:00
Dennis Schwerdel 8e3cdbddbf Formatting 2021-01-23 21:03:36 +01:00
Dennis Schwerdel e6994e6939 Implement event scripts 2021-01-23 20:29:15 +01:00
dswd a6cc124c56
Merge pull request #139 from dswd/dependabot/cargo/serde-1.0.120
Bump serde from 1.0.119 to 1.0.120
2021-01-22 16:06:08 +01:00
dswd 041368994f
Merge pull request #140 from dswd/dependabot/cargo/serde_derive-1.0.120
Bump serde_derive from 1.0.119 to 1.0.120
2021-01-22 16:05:51 +01:00
dependabot[bot] 4e146065e1
Bump serde from 1.0.119 to 1.0.120
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.119 to 1.0.120.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.119...v1.0.120)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-20 05:11:34 +00:00
dependabot[bot] a664d60e1e
Bump serde_derive from 1.0.119 to 1.0.120
Bumps [serde_derive](https://github.com/serde-rs/serde) from 1.0.119 to 1.0.120.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.119...v1.0.120)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-20 05:11:34 +00:00
Dennis Schwerdel 285940c60a Support for creating shell completions 2021-01-16 23:44:43 +01:00
dswd e6f10929b7
Merge pull request #137 from dswd/dependabot/cargo/rand-0.8.2
Bump rand from 0.8.1 to 0.8.2
2021-01-14 11:54:12 +01:00
dependabot[bot] 386250576f
Bump rand from 0.8.1 to 0.8.2
Bumps [rand](https://github.com/rust-random/rand) from 0.8.1 to 0.8.2.
- [Release notes](https://github.com/rust-random/rand/releases)
- [Changelog](https://github.com/rust-random/rand/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-random/rand/compare/0.8.1...0.8.2)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-14 05:23:39 +00:00
Dennis Schwerdel c941f9c56d Update deps & rust 2021-01-13 09:23:38 +01:00
dswd c5626e75ac
Merge pull request #134 from dswd/dependabot/cargo/serde-1.0.119
Bump serde from 1.0.118 to 1.0.119
2021-01-13 08:57:19 +01:00
dswd 4c56917d1e
Merge pull request #133 from dswd/dependabot/cargo/serde_derive-1.0.119
Bump serde_derive from 1.0.118 to 1.0.119
2021-01-13 08:57:07 +01:00
dependabot[bot] 57d26944fb
Bump serde_derive from 1.0.118 to 1.0.119
Bumps [serde_derive](https://github.com/serde-rs/serde) from 1.0.118 to 1.0.119.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.118...v1.0.119)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-13 07:26:30 +00:00
dependabot[bot] e2a2579322
Bump serde from 1.0.118 to 1.0.119
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.118 to 1.0.119.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.118...v1.0.119)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-13 07:24:55 +00:00
dswd 3b95cc0fc3
Merge pull request #135 from dswd/dependabot/cargo/log-0.4.13
Bump log from 0.4.11 to 0.4.13
2021-01-13 08:20:42 +01:00
dswd 895d14615a
Merge pull request #136 from dswd/dependabot/cargo/tempfile-3.2.0
Bump tempfile from 3.1.0 to 3.2.0
2021-01-13 08:20:32 +01:00
dependabot[bot] a06157930a
Bump tempfile from 3.1.0 to 3.2.0
Bumps [tempfile](https://github.com/Stebalien/tempfile) from 3.1.0 to 3.2.0.
- [Release notes](https://github.com/Stebalien/tempfile/releases)
- [Changelog](https://github.com/Stebalien/tempfile/blob/master/NEWS)
- [Commits](https://github.com/Stebalien/tempfile/commits)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-13 05:27:12 +00:00
dependabot[bot] 3d28d9e188
Bump log from 0.4.11 to 0.4.13
Bumps [log](https://github.com/rust-lang/log) from 0.4.11 to 0.4.13.
- [Release notes](https://github.com/rust-lang/log/releases)
- [Changelog](https://github.com/rust-lang/log/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/log/compare/0.4.11...0.4.13)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-12 05:28:53 +00:00
dswd 3ca6926124
Merge pull request #130 from dswd/dependabot/cargo/byteorder-1.4.2
Bump byteorder from 1.3.4 to 1.4.2
2021-01-11 20:04:23 +01:00
dswd 4ea69b8a2e
Merge pull request #132 from dswd/dependabot/cargo/smallvec-1.6.1
Bump smallvec from 1.6.0 to 1.6.1
2021-01-11 20:03:42 +01:00
dependabot[bot] 107c3cac34
Bump byteorder from 1.3.4 to 1.4.2
Bumps [byteorder](https://github.com/BurntSushi/byteorder) from 1.3.4 to 1.4.2.
- [Release notes](https://github.com/BurntSushi/byteorder/releases)
- [Changelog](https://github.com/BurntSushi/byteorder/blob/master/CHANGELOG.md)
- [Commits](https://github.com/BurntSushi/byteorder/compare/1.3.4...1.4.2)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-11 05:41:07 +00:00
dependabot[bot] 3effd360a2
Bump smallvec from 1.6.0 to 1.6.1
Bumps [smallvec](https://github.com/servo/rust-smallvec) from 1.6.0 to 1.6.1.
- [Release notes](https://github.com/servo/rust-smallvec/releases)
- [Commits](https://github.com/servo/rust-smallvec/compare/v1.6.0...v1.6.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-11 05:41:07 +00:00
dswd 2450cc39c5
Merge pull request #129 from dswd/dependabot/cargo/libc-0.2.82
Bump libc from 0.2.81 to 0.2.82
2021-01-08 09:28:29 +01:00
dependabot[bot] 23af339343
Bump libc from 0.2.81 to 0.2.82
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.81 to 0.2.82.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.81...0.2.82)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-08 05:24:33 +00:00
dswd 577500fb0b
Merge pull request #128 from dswd/dependabot/cargo/serde_yaml-0.8.15
Bump serde_yaml from 0.8.14 to 0.8.15
2021-01-06 07:53:05 +01:00
dependabot[bot] cc823ed330
Bump serde_yaml from 0.8.14 to 0.8.15
Bumps [serde_yaml](https://github.com/dtolnay/serde-yaml) from 0.8.14 to 0.8.15.
- [Release notes](https://github.com/dtolnay/serde-yaml/releases)
- [Commits](https://github.com/dtolnay/serde-yaml/compare/0.8.14...0.8.15)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-06 05:07:39 +00:00
dswd 8f77db8104
Merge pull request #127 from dswd/dependabot/cargo/rand-0.8.1
Bump rand from 0.8.0 to 0.8.1
2021-01-05 08:24:07 +01:00
dependabot[bot] 80cb58f4c6
Bump rand from 0.8.0 to 0.8.1
Bumps [rand](https://github.com/rust-random/rand) from 0.8.0 to 0.8.1.
- [Release notes](https://github.com/rust-random/rand/releases)
- [Changelog](https://github.com/rust-random/rand/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-random/rand/compare/0.8.0...0.8.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-05 05:17:41 +00:00
dswd c2dd3d9d08
Merge pull request #125 from dswd/dependabot/cargo/smallvec-1.6.0
Bump smallvec from 1.5.1 to 1.6.0
2021-01-04 07:57:51 +01:00
dswd de1e556d02
Merge pull request #126 from dswd/dependabot/cargo/yaml-rust-0.4.5
Bump yaml-rust from 0.4.4 to 0.4.5
2021-01-04 07:57:09 +01:00
dependabot[bot] 8252724feb
Bump yaml-rust from 0.4.4 to 0.4.5
Bumps [yaml-rust](https://github.com/chyh1990/yaml-rust) from 0.4.4 to 0.4.5.
- [Release notes](https://github.com/chyh1990/yaml-rust/releases)
- [Commits](https://github.com/chyh1990/yaml-rust/compare/0.4.4...0.4.5)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-04 05:43:53 +00:00
dependabot[bot] b85c935d4d
Bump smallvec from 1.5.1 to 1.6.0
Bumps [smallvec](https://github.com/servo/rust-smallvec) from 1.5.1 to 1.6.0.
- [Release notes](https://github.com/servo/rust-smallvec/releases)
- [Commits](https://github.com/servo/rust-smallvec/compare/v1.5.1...v1.6.0)

Signed-off-by: dependabot[bot] <support@github.com>
2021-01-01 05:47:44 +00:00
dswd 517348edee
Merge pull request #123 from dswd/dependabot/cargo/thiserror-1.0.23
Bump thiserror from 1.0.22 to 1.0.23
2020-12-30 10:53:41 +01:00
dswd e9770887af
Merge pull request #124 from dswd/dependabot/cargo/igd-0.12.0
Bump igd from 0.11.1 to 0.12.0
2020-12-30 10:53:14 +01:00
dependabot[bot] 8902db6a3a
Bump igd from 0.11.1 to 0.12.0
Bumps [igd](https://github.com/sbstp/rust-igd) from 0.11.1 to 0.12.0.
- [Release notes](https://github.com/sbstp/rust-igd/releases)
- [Commits](https://github.com/sbstp/rust-igd/compare/v0.11.1...v0.12.0)

Signed-off-by: dependabot[bot] <support@github.com>
2020-12-28 05:48:59 +00:00
dependabot[bot] 99163cad80
Bump thiserror from 1.0.22 to 1.0.23
Bumps [thiserror](https://github.com/dtolnay/thiserror) from 1.0.22 to 1.0.23.
- [Release notes](https://github.com/dtolnay/thiserror/releases)
- [Commits](https://github.com/dtolnay/thiserror/compare/1.0.22...1.0.23)

Signed-off-by: dependabot[bot] <support@github.com>
2020-12-28 05:48:56 +00:00
Dennis Schwerdel 124f7cbff9 Almost works 2020-12-20 13:28:01 +01:00
Dennis Schwerdel d50490ac51 Client works 2020-12-20 01:40:32 +01:00
Dennis Schwerdel edd0e7a29f Update rust to 1.48.0 2020-12-19 22:38:34 +00:00
Dennis Schwerdel f5888d9df6 Update deps 2020-12-19 22:34:17 +00:00
dswd 2416f8e47a
Merge pull request #119 from dswd/dependabot/cargo/libc-0.2.81
Bump libc from 0.2.80 to 0.2.81
2020-12-19 23:29:40 +01:00
dswd 242b65f527
Merge pull request #118 from dswd/dependabot/cargo/serde_derive-1.0.118
Bump serde_derive from 1.0.117 to 1.0.118
2020-12-19 23:29:31 +01:00
dswd 06014b4751
Merge pull request #120 from dswd/dependabot/cargo/serde-1.0.118
Bump serde from 1.0.117 to 1.0.118
2020-12-19 23:29:21 +01:00
dswd 3e7b53a369
Merge pull request #121 from dswd/dependabot/cargo/smallvec-1.5.1
Bump smallvec from 1.5.0 to 1.5.1
2020-12-19 23:29:10 +01:00
Dennis Schwerdel 6d1bb8fabb Exchange all peer addresses 2020-12-19 10:54:55 +00:00
dependabot[bot] 4365f408b5
Bump smallvec from 1.5.0 to 1.5.1
Bumps [smallvec](https://github.com/servo/rust-smallvec) from 1.5.0 to 1.5.1.
- [Release notes](https://github.com/servo/rust-smallvec/releases)
- [Commits](https://github.com/servo/rust-smallvec/compare/v1.5.0...v1.5.1)

Signed-off-by: dependabot[bot] <support@github.com>
2020-12-07 05:51:26 +00:00
dependabot[bot] e71b6b7149
Bump serde from 1.0.117 to 1.0.118
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.117 to 1.0.118.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.117...v1.0.118)

Signed-off-by: dependabot[bot] <support@github.com>
2020-12-07 05:51:23 +00:00
dependabot[bot] e6fdc737fa
Bump libc from 0.2.80 to 0.2.81
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.80 to 0.2.81.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.80...0.2.81)

Signed-off-by: dependabot[bot] <support@github.com>
2020-12-07 05:51:19 +00:00
dependabot[bot] 87b54f1c3f
Bump serde_derive from 1.0.117 to 1.0.118
Bumps [serde_derive](https://github.com/serde-rs/serde) from 1.0.117 to 1.0.118.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.117...v1.0.118)

Signed-off-by: dependabot[bot] <support@github.com>
2020-12-07 05:51:14 +00:00
Dennis Schwerdel 70ad35932c Update readme 2020-12-03 18:04:32 +00:00
dswd e689d9f492
Merge pull request #117 from dswd/dependabot/cargo/ring-0.16.19
Bump ring from 0.16.18 to 0.16.19
2020-12-02 08:42:08 +01:00
dswd 0fea65a25d
Merge pull request #116 from dswd/dependabot/cargo/structopt-0.3.21
Bump structopt from 0.3.20 to 0.3.21
2020-12-02 08:41:56 +01:00
dependabot[bot] 329bf4de3e
Bump ring from 0.16.18 to 0.16.19
Bumps [ring](https://github.com/briansmith/ring) from 0.16.18 to 0.16.19.
- [Release notes](https://github.com/briansmith/ring/releases)
- [Commits](https://github.com/briansmith/ring/commits)

Signed-off-by: dependabot[bot] <support@github.com>
2020-12-02 05:28:34 +00:00
Dennis Schwerdel 26689a3003 Add dev container config 2020-12-01 22:27:13 +00:00
dependabot[bot] b13089d5c4
Bump structopt from 0.3.20 to 0.3.21
Bumps [structopt](https://github.com/TeXitoi/structopt) from 0.3.20 to 0.3.21.
- [Release notes](https://github.com/TeXitoi/structopt/releases)
- [Changelog](https://github.com/TeXitoi/structopt/blob/master/CHANGELOG.md)
- [Commits](https://github.com/TeXitoi/structopt/compare/v0.3.20...v0.3.21)

Signed-off-by: dependabot[bot] <support@github.com>
2020-12-01 05:47:03 +00:00
Dennis Schwerdel ea049e4a4c Remove dummy device type 2020-11-28 23:47:43 +01:00
Dennis Schwerdel d3402e1f50 Lock time to last working version 2020-11-28 23:37:28 +01:00
dswd 5751a2999f
Merge pull request #114 from dswd/dependabot/cargo/ring-0.16.18
Bump ring from 0.16.15 to 0.16.18
2020-11-27 08:23:05 +01:00
dependabot[bot] a4ebff84af
Bump ring from 0.16.15 to 0.16.18
Bumps [ring](https://github.com/briansmith/ring) from 0.16.15 to 0.16.18.
- [Release notes](https://github.com/briansmith/ring/releases)
- [Commits](https://github.com/briansmith/ring/commits)

Signed-off-by: dependabot[bot] <support@github.com>
2020-11-27 05:27:35 +00:00
dswd 7184a64ce3
Merge pull request #110 from dswd/dependabot/cargo/smallvec-1.5.0
Bump smallvec from 1.4.2 to 1.5.0
2020-11-26 16:29:12 +01:00
dependabot[bot] 1e9ace409f
Bump smallvec from 1.4.2 to 1.5.0
Bumps [smallvec](https://github.com/servo/rust-smallvec) from 1.4.2 to 1.5.0.
- [Release notes](https://github.com/servo/rust-smallvec/releases)
- [Commits](https://github.com/servo/rust-smallvec/compare/v1.4.2...v1.5.0)

Signed-off-by: dependabot[bot] <support@github.com>
2020-11-18 05:30:43 +00:00
Dennis Schwerdel ea5d515ffd Use specific version of asciidoctor that works 2020-11-07 12:59:44 +01:00
87 changed files with 5759 additions and 3787 deletions

View File

@ -1,14 +0,0 @@
[target.armv7-unknown-linux-gnueabihf]
linker = "arm-linux-gnueabihf-gcc"
objcopy = { path = "arm-linux-gnueabihf-objcopy" }
strip = { path = "arm-linux-gnueabihf-strip" }
[target.arm-unknown-linux-gnueabihf]
linker = "arm-linux-gnueabihf-gcc"
objcopy = { path = "arm-linux-gnueabihf-objcopy" }
strip = { path = "arm-linux-gnueabihf-strip" }
[target.aarch64-unknown-linux-gnu]
linker = "aarch64-linux-gnu-gcc"
objcopy = { path = "aarch64-linux-gnu-objcopy" }
strip = { path = "aarch64-linux-gnu-strip" }

27
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@ -0,0 +1,27 @@
---
name: Bug report
about: Report a bug
title: ''
labels: ''
assignees: ''
---
### Describe the bug
A clear and concise description of what the bug is.
### Details of your setup
**VpnCloud version:**
**Description of your VPN setup**
- How many nodes?
- Any NAT involved?
- Any custom routing?
**Config file contents**
normally in `/etc/vpncloud/MYNET.net`
:bangbang: make sure to mask (`***`) passwords and public IPs/hostnames :bangbang:
**Log entries**
normally in `/var/log/vpncloud.MYNET.log`

8
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@ -0,0 +1,8 @@
blank_issues_enabled: false
contact_links:
- name: VpnCloud Documentation
url: https://vpncloud.ddswd.de/docs
about: Please check the documentation before asking how things work.
- name: Discussion Group on GitHub
url: https://github.com/dswd/vpncloud/discussions
about: Please discuss or ask anything there that is not an issue.

View File

@ -0,0 +1,16 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
** Describe the high-level goal you want to achieve **
I would like to...
** Describe the proposed solution **
I propose to...

View File

@ -0,0 +1,14 @@
---
name: Other issue
about: Any other issue
title: ''
labels: ''
assignees: ''
---
### Describe your issue
👉 Please use the [Discussion group](https://github.com/dswd/vpncloud/discussions) if you...
* just want to ask a question
* want to discuss a new feature

View File

@ -6,14 +6,14 @@ RUN apt-get update \
curl \
gcc-aarch64-linux-gnu \
gcc-arm-linux-gnueabihf \
gcc-arm-linux-gnueabi \
libc6-dev-arm64-cross \
libc6-dev-armhf-cross \
libc6-dev-armel-cross \
libc6-dev-i386 \
gcc-5-multilib \
asciidoctor \
&& rm -rf /var/cache/dpkg
RUN ln -s asm-generic/ /usr/include/asm
&& apt-get clean && rm -rf /var/lib/apt/lists/*
ADD entrypoint.sh /entrypoint.sh

View File

@ -1,11 +1,5 @@
name: 'build-deb'
description: 'Create deb packages'
inputs:
rust:
description: Rust version
default: 'stable'
runs:
using: 'docker'
image: 'Dockerfile'
env:
RUST: ${{ inputs.rust }}

View File

@ -2,31 +2,36 @@
set -e
curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain ${RUST}
TOOLCHAIN=$(grep -e '^toolchain =' Cargo.toml | sed -e 's/toolchain = "\(.*\)"/\1/')
VERSION=$(grep -e '^version =' Cargo.toml | sed -e 's/version = "\(.*\)"/\1/')
DEB_VERSION=$(echo "$VERSION" | sed -e 's/-/~/g')
ln -s asm-generic/ /usr/include/asm
curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain ${TOOLCHAIN}
source $HOME/.cargo/env
rustup target add i686-unknown-linux-gnu
rustup target add armv5te-unknown-linux-gnueabi
rustup target add armv7-unknown-linux-gnueabihf
rustup target add aarch64-unknown-linux-gnu
cargo install cargo-deb
VERSION=$(grep -e '^version =' Cargo.toml | sed -e 's/version = "\(.*\)"/\1/')
DEB_VERSION=$(echo "$VERSION" | sed -e 's/-/~/g')
mkdir dist
build_deb() {
ARCH=$1
TARGET=$2
cargo deb --target ${TARGET}
cp target/${TARGET}/debian/vpncloud_${DEB_VERSION}_${ARCH}.deb dist/vpncloud_${DEB_VERSION}_${ARCH}.deb
}
cargo deb
cp target/debian/vpncloud_${DEB_VERSION}_amd64.deb dist/vpncloud_${DEB_VERSION}_amd64.deb
# i386 deb
cargo deb --target i686-unknown-linux-gnu
cp target/i686-unknown-linux-gnu/debian/vpncloud_${DEB_VERSION}_i386.deb dist/vpncloud_${DEB_VERSION}_i386.deb
# arm7hf deb
cargo deb --target armv7-unknown-linux-gnueabihf
cp target/armv7-unknown-linux-gnueabihf/debian/vpncloud_${DEB_VERSION}_armhf.deb dist/vpncloud_${DEB_VERSION}_armhf.deb
# aarch64 deb
cargo deb --target aarch64-unknown-linux-gnu
cp target/aarch64-unknown-linux-gnu/debian/vpncloud_${DEB_VERSION}_arm64.deb dist/vpncloud_${DEB_VERSION}_arm64.deb
build_deb i386 i686-unknown-linux-gnu
build_deb armhf armv7-unknown-linux-gnueabihf
build_deb armel armv5te-unknown-linux-gnueabi
build_deb arm64 aarch64-unknown-linux-gnu

View File

@ -1,7 +1,12 @@
FROM centos:7
RUN yum groupinstall -y 'Development Tools'
RUN yum install -y ruby && gem install asciidoctor
RUN yum install -y ruby && gem install asciidoctor -v 2.0.10
RUN yum install -y libstdc++-*.i686 \
&& yum install -y glibc-*.i686 \
&& yum install -y libgcc.i686
RUN ln -s /usr/bin/gcc /usr/bin/i686-linux-gnu-gcc
ADD entrypoint.sh /entrypoint.sh

View File

@ -1,11 +1,5 @@
name: 'build-deb'
description: 'Create deb packages'
inputs:
rust:
description: Rust version
default: 'stable'
runs:
using: 'docker'
image: 'Dockerfile'
env:
RUST: ${{ inputs.rust }}

View File

@ -2,13 +2,7 @@
set -e
curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain ${RUST}
source $HOME/.cargo/env
rustup target add i686-unknown-linux-gnu
rustup target add armv7-unknown-linux-gnueabihf
cargo install cargo-rpm
TOOLCHAIN=$(grep -e '^toolchain =' Cargo.toml | sed -e 's/toolchain = "\(.*\)"/\1/')
VERSION=$(grep -e '^version =' Cargo.toml | sed -e 's/version = "\(.*\)"/\1/')
if echo "$VERSION" | fgrep -q "-"; then
@ -17,8 +11,31 @@ else
RPM_VERSION="$VERSION-1"
fi
curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain ${TOOLCHAIN}
source $HOME/.cargo/env
rustup target add i686-unknown-linux-gnu
rustup target add armv7-unknown-linux-gnueabihf
cargo install cargo-rpm
mkdir dist
cargo build --release
cargo rpm build
cp target/release/rpmbuild/RPMS/x86_64/vpncloud-${RPM_VERSION}.x86_64.rpm dist/vpncloud_${RPM_VERSION}.x86_64.rpm
build_rpm() {
ARCH=$1
TARGET=$2
if ! [ -f dist/vpncloud_${RPM_VERSION}.${ARCH}.rpm ]; then
mkdir -p target
[ -L target/assets ] || ln -s ../assets target/assets
[ -L target/target ] || ln -s ../target target/target
cargo rpm build --target ${TARGET}
cp target/${TARGET}/release/rpmbuild/RPMS/${ARCH}/vpncloud-${RPM_VERSION}.${ARCH}.rpm dist/vpncloud_${RPM_VERSION}.${ARCH}.rpm
fi
}
build_rpm i686 i686-unknown-linux-gnu

21
.github/actions/build-static/Dockerfile vendored Normal file
View File

@ -0,0 +1,21 @@
FROM ubuntu:16.04
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
build-essential \
curl \
gcc-aarch64-linux-gnu \
gcc-arm-linux-gnueabihf \
gcc-arm-linux-gnueabi \
libc6-dev-arm64-cross \
libc6-dev-armhf-cross \
libc6-dev-armel-cross \
libc6-dev-i386 \
gcc-5-multilib \
asciidoctor \
musl musl-dev musl-tools \
&& apt-get clean && rm -rf /var/lib/apt/lists/*
ADD entrypoint.sh /entrypoint.sh
ENTRYPOINT /entrypoint.sh

View File

@ -0,0 +1,5 @@
name: 'build-static'
description: 'Create static binaries'
runs:
using: 'docker'
image: 'Dockerfile'

39
.github/actions/build-static/entrypoint.sh vendored Executable file
View File

@ -0,0 +1,39 @@
#!/bin/bash
set -e
TOOLCHAIN=$(grep -e '^toolchain =' Cargo.toml | sed -e 's/toolchain = "\(.*\)"/\1/')
UPX_VERSION=$(grep -e '^upx_version =' Cargo.toml | sed -e 's/upx_version = "\(.*\)"/\1/')
VERSION=$(grep -e '^version =' Cargo.toml | sed -e 's/version = "\(.*\)"/\1/')
DEB_VERSION=$(echo "$VERSION" | sed -e 's/-/~/g')
ln -s asm-generic/ /usr/include/asm
ln -s /usr/bin/aarch64-linux-gnu-gcc /usr/bin/aarch64-linux-musl-gcc
ln -s /usr/bin/arm-linux-gnueabihf-gcc /usr/bin/arm-linux-musleabihf-gcc
curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain ${TOOLCHAIN}
source $HOME/.cargo/env
rustup target add x86_64-unknown-linux-musl
rustup target add i686-unknown-linux-musl
rustup target add armv5te-unknown-linux-musleabi
rustup target add armv7-unknown-linux-musleabihf
rustup target add aarch64-unknown-linux-musl
curl https://github.com/upx/upx/releases/download/v${UPX_VERSION}/upx-${UPX_VERSION}-amd64_linux.tar.xz -Lf | tar -xJ --strip-components=1 -C /usr/bin
mkdir dist
build_static() {
ARCH=$1
TARGET=$2
cargo build --release --features installer --target ${TARGET} && upx --lzma target/${TARGET}/release/vpncloud
cp target/${TARGET}/release/vpncloud ../dist/vpncloud_${VERSION}_static_${ARCH}
}
build_static amd64 x86_64-unknown-linux-musl
#build_static i386 i686-unknown-linux-musl
build_static armhf armv7-unknown-linux-musleabihf
build_static armel armv5te-unknown-linux-musleabi
build_static arm64 aarch64-unknown-linux-musl

View File

@ -6,7 +6,7 @@ jobs:
audit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions/checkout@v2
- uses: actions-rs/audit-check@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}

View File

@ -18,6 +18,9 @@ jobs:
name: Test Suite
runs-on: ubuntu-latest
steps:
- uses: szenius/set-timezone@v1.0
with:
timezoneLinux: Europe/Berlin
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
@ -26,24 +29,4 @@ jobs:
override: true
- uses: actions-rs/cargo@v1
with:
command: test
coverage:
name: Coverage
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Install stable toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
- name: Run cargo-tarpaulin
uses: actions-rs/tarpaulin@v0.1
with:
args: '-o Html -- --test-threads=1'
- name: Archive code coverage results
uses: actions/upload-artifact@v1
with:
name: code-coverage-report
path: tarpaulin-report.html
command: test

View File

@ -1,45 +0,0 @@
on:
release:
types: [created]
name: Build packages
jobs:
deb:
name: "Build deb packages"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run builder
uses: ./.github/actions/build-deb
with:
rust: '1.47.0'
- name: Archive artifacts
uses: actions/upload-artifact@v1
with:
name: packages
path: dist
- name: Upload artifacts
uses: skx/github-action-publish-binaries@master
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
args: 'dist/*.deb'
rpm:
name: "Build rpm packages"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run builder
uses: ./.github/actions/build-rpm
with:
rust: '1.47.0'
- name: Archive artifacts
uses: actions/upload-artifact@v1
with:
name: packages
path: dist
- name: Upload artifacts
uses: skx/github-action-publish-binaries@master
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
args: 'dist/*.rpm'

View File

@ -1,44 +0,0 @@
%define __spec_install_post %{nil}
%define __os_install_post %{_dbpath}/brp-compress
%define debug_package %{nil}
Name: vpncloud
Summary: Peer-to-peer VPN
Version: @@VERSION@@
Release: @@RELEASE@@
License: GPL-3.0
Group: Applications/System
Source0: %{name}-%{version}.tar.gz
URL: https://vpncloud.ddswd.de
BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root
%description
%{summary}
%prep
%setup -q
%install
rm -rf %{buildroot}
mkdir -p %{buildroot}
mkdir -p %{buildroot}/etc/vpncloud
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}/../../../../../target/vpncloud.1.gz %{buildroot}/usr/share/man/man1/vpncloud.1.gz
cp -a * %{buildroot}
%clean
rm -rf %{buildroot}
%files
/etc/vpncloud
/etc/vpncloud/example.net.disabled
/usr/bin/vpncloud
/lib/systemd/system/vpncloud@.service
/usr/share/man/man1/vpncloud.1.gz
%defattr(-,root,root,-)
%{_bindir}/*

View File

@ -2,6 +2,45 @@
This project follows [semantic versioning](http://semver.org).
### UNRELEASED
- [changed] Changed Rust version to 1.75.0
- [changed] Updated dependencies
- [fixed] Fix error when IPv6 is not available
### v2.3.0 (2021-12-23)
- [added] Added build for armv5te (thanks to xek)
- [added] Option to specify advertised addresses
- [added] Peers now learn their own address from peers
- [changed] Changed Rust version to 1.57.0
- [changed] Updated dependencies
- [fixed] Fixed problem with IPv4 addresses in listen option
- [fixed] Fixed periodic broadcast messages in switch mode
### v2.2.0 (2021-04-06)
- [added] Service target file (thanks to mnhauke)
- [added] Added interactive configuration wizard
- [added] Support for (un-)installation
- [added] Building static binaries
- [added] Building i686 rpm
- [changed] Restructured example config
- [changed] Changed Rust version to 1.51.0
- [changed] Updated dependencies
- [changed] Change permissions of /etc/vpncloud
### v2.1.0 (2021-02-06)
- [added] Support for websocket proxy mode
- [added] Support for hook scripts to handle certain situations
- [added] Support for creating shell completions
- [removed] Removed dummy device type
- [changed] Updated dependencies
- [changed] Changed Rust version to 1.49.0
- [fixed] Added missing peer address propagation
- [fixed] Fixed problem with peer addresses without port
### v2.0.1 (2020-11-07)
- [changed] Changed documentation

1210
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,46 +1,65 @@
[package]
name = "vpncloud"
version = "2.0.1"
version = "2.4.0"
authors = ["Dennis Schwerdel <schwerdel@googlemail.com>"]
build = "build.rs"
license = "GPL-3.0"
description = "Peer-to-peer VPN"
homepage = "https://vpncloud.ddswd.de"
repository = "https://github.com/dswd/vpncloud"
keywords = ["vpn", "p2p", "tun", "tap", "network"]
readme = "README.md"
edition = "2018"
edition = "2021"
[package.metadata]
toolchain = "1.75.0"
upx_version = "4.2.2"
[dependencies]
time = "0.2"
chrono = { version = "0.4", features = ["std", "clock"], default_features = false}
structopt = "0.3"
serde = "1.0"
serde_derive = "1.0"
serde_yaml = "0.8"
serde = { version = "1.0", features = ["derive"] }
serde_yaml = "0.9"
log = { version = "0.4", features = ["std"] }
signal = "0.7"
libc = "0.2"
rand = "0.7"
rand = "0.8"
fnv = "1"
yaml-rust = "0.4"
igd = { version = "0.11", optional = true }
daemonize = "0.4"
ring = "0.16"
daemonize = "0.5"
ring = "0.17"
privdrop = "0.5"
byteorder = "1.3"
byteorder = "1.4"
thiserror = "1.0"
smallvec = "1.4"
smallvec = "1.7"
dialoguer = { version = "0.11", optional = true }
tungstenite = { version = "0.21", optional = true }
url = { version = "2.2", optional = true }
igd = { version = "0.12", optional = true }
[dev-dependencies]
tempfile = "3"
criterion = { version = "0.5", features = ["html_reports"] }
iai = "0.1"
[features]
default = ["nat"]
bench = []
default = ["nat", "websocket", "wizard"]
nat = ["igd"]
websocket = ["tungstenite", "url"]
wizard = ["dialoguer"]
installer = []
[[bench]]
name = "criterion"
harness = false
[[bench]]
name = "valgrind"
harness = false
[profile.release]
lto = true
strip = true
[profile.dev]
lto = false
@ -50,10 +69,12 @@ lto = false
[package.metadata.deb]
extended-description = """\
VpnCloud 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. VpnCloud
establishes a fully-meshed VPN network in a peer-to-peer manner. It can work
on TUN devices (IP based) and TAP devices (Ethernet based)."""
VpnCloud is a high performance peer-to-peer mesh VPN over UDP supporting strong encryption,
NAT traversal and a simple configuration. It establishes a fully-meshed self-healing VPN
network in a peer-to-peer manner with strong end-to-end encryption based on elliptic curve
keys and AES-256. VpnCloud creates a virtual network interface on the host and forwards all
received data via UDP to the destination. It can work on TUN devices (IP based) and TAP
devices (Ethernet based)."""
license-file = ["LICENSE.md", "1"]
changelog = "assets/changelog.txt"
section = "net"
@ -63,11 +84,18 @@ 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.target", "/lib/systemd/system/vpncloud.target", "644"],
["assets/vpncloud-wsproxy.service", "/lib/systemd/system/vpncloud-wsproxy.service", "644"],
["target/vpncloud.1.gz", "/usr/share/man/man1/vpncloud.1.gz", "644"]
]
[package.metadata.rpm.cargo]
buildflags = ["--release"]
[package.metadata.rpm.targets]
vpncloud = { path = "/usr/bin/vpncloud" }
[package.metadata.generate-rpm]
assets = [
{ source = "target/release/vpncloud", dest = "/usr/bin/vpncloud", mode = "755" },
{ source = "assets/example.net.disabled", dest = "/etc/vpncloud/example.net.disabled", mode = "600" },
{ source = "assets/vpncloud@.service", dest = "/lib/systemd/system/vpncloud@.service", mode = "644" },
{ source = "assets/vpncloud.target", dest = "/lib/systemd/system/vpncloud.target", mode = "644" },
{ source = "assets/vpncloud-wsproxy.service", dest = "/lib/systemd/system/vpncloud-wsproxy.service", mode = "644" },
{ source = "target/vpncloud.1.gz", dest = "/usr/share/man/man1/vpncloud.1.gz", mode = "644" }
]
auto-req = "no"

File diff suppressed because it is too large Load Diff

View File

@ -3,44 +3,44 @@ VpnCloud - Peer-to-Peer VPN
![Checks](https://github.com/dswd/vpncloud/workflows/Checks/badge.svg?branch=master)
![Security audit](https://github.com/dswd/vpncloud/workflows/Security%20audit/badge.svg?branch=master)
**VpnCloud** 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. VpnCloud
establishes an encrypted fully-meshed VPN network in a peer-to-peer manner.
It can work on TUN devices (IP based) and TAP devices (Ethernet based).
Tunneling traffic between two nodes can be as easy as:
**VpnCloud** is a high performance peer-to-peer mesh VPN over UDP supporting strong encryption, NAT traversal and a simple configuration. It establishes a fully-meshed self-healing VPN network in a peer-to-peer manner with strong end-to-end encryption based on elliptic curve keys and AES-256. VpnCloud creates a virtual network interface on the host and forwards all received data via UDP to the destination. It can work on TUN devices (IP based) and TAP devices (Ethernet based).
$> vpncloud -c REMOTE_HOST:PORT -p 'mypassword' --ip 10.0.0.1/24
```sh
$> vpncloud -c REMOTE_HOST:PORT -p 'mypassword' --ip 10.0.0.1/24
```
or as config file:
crypto:
password: mysecret
ip: 10.0.0.1
peers:
- REMOTE_HOST:PORT
```yaml
crypto:
password: mysecret
ip: 10.0.0.1
peers:
- REMOTE_HOST:PORT
```
For more information, please see the [Website](https://vpncloud.ddswd.de) or the [Forum](https://groups.google.com/forum/#!forum/vpncloud).
For more information, please see the [Website](https://vpncloud.ddswd.de) or the [Discussions group](https://github.com/dswd/vpncloud/discussions).
### Project Status
This project is still [under development](CHANGELOG.md) but has reached a
somewhat stable state. VpnCloud features the following functionality:
* Setting up tunnels between two networks via Ethernet (TAP) and IP (TUN)
* Connecting multiple networks with multiple forwarding behaviors (Hub, Switch,
Router)
* Strong encryption using Curve25519 key pairs and AES methods
* Automatic peer-to-peer meshing, no central servers
* NAT and (limited) firewall traversal using hole punching
* Automatic reconnecting when connections are lost
* Non-native forwarding modes, e.g. IP based learning switch and prefix routed
Ethernet networks.
* Connecting hundreds of nodes with the VPN
* High throughput and low additional latency (see [performance page](https://vpncloud.ddswd.de/features/performance))
* Support for tunneled VLans (TAP device)
* Creating virtual network interfaces based on Ethernet (TAP) and IP (TUN)
* Strong end-to-end encryption using Curve25519 key pairs and AES methods
* Support for different forwarding/routing behaviors (Hub, Switch, Router)
* NAT and firewall traversal using hole punching
* Automatic port forwarding via UPnP
* Websocket proxy mode for restrictive environments
* Support for tunneled VLans (TAP devices)
* Support for publishing [beacons](https://vpncloud.ddswd.de/docs/beacons) to help nodes find each others
* Support for statsd monitoring
* Low memory footprint
* Single binary, no dependencies, no kernel module
### Installing
@ -62,6 +62,9 @@ contributions are very welcome:
* **Linux packages**: VpnCloud is stable enough to be packaged for Linux
distributions. Maintainers who want to package VpnCloud are very welcome.
* **Help with other platforms**: If you are a Rust developer with experience
on Windows or MacOS your help on porting VpnCloud to those platforms is very
welcome.
* **Security review**: The security has been implemented with strong security
primitives but it would be great if a cryptography expert could verify the
system.

View File

@ -1,3 +1,42 @@
vpncloud (2.3.0) stable; urgency=medium
* [added] Added build for armv5te (thanks to xek)
* [added] Option to specify advertised addresses
* [added] Peers now learn their own address from peers
* [changed] Changed Rust version to 1.57.0
* [changed] Updated dependencies
* [fixed] Fixed problem with IPv4 addresses in listen option
* [fixed] Fixed periodic broadcast messages in switch mode
-- Dennis Schwerdel <schwerdel+vpncloud@googlemail.com> Thu, 23 Dec 2021 20:41:00 +0100
vpncloud (2.2.0) stable; urgency=medium
* [added] Service target file (thanks to mnhauke)
* [added] Added interactive configuration wizard
* [added] Support for (un-)installation
* [added] Building static binaries
* [added] Building i686 rpm
* [changed] Restructured example config
* [changed] Changed Rust version to 1.51.0
* [changed] Updated dependencies
* [changed] Change permissions of /etc/vpncloud
-- Dennis Schwerdel <schwerdel+vpncloud@googlemail.com> Tue, 06 Apr 2021 12:27:00 +0200
vpncloud (2.1.0) stable; urgency=medium
* [added] Support for websocket proxy mode
* [added] Support for hook scripts to handle certain situations
* [added] Support for creating shell completions
* [removed] Removed dummy device type
* [changed] Updated dependencies
* [changed] Changed Rust version to 1.49.0
* [fixed] Added missing peer address propagation
* [fixed] Fixed problem with peer addresses without port
-- Dennis Schwerdel <schwerdel@googlemail.com> Sat, 06 Feb 2021 13:13:00 +0100
vpncloud (2.0.1) stable; urgency=medium
* [changed] Changed documentation

View File

@ -1,3 +1,4 @@
#!/bin/bash
systemctl daemon-reload
systemctl daemon-reload
chmod 700 /etc/vpncloud

View File

@ -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

View File

@ -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

View File

@ -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)

2
assets/vpncloud.target Normal file
View File

@ -0,0 +1,2 @@
[Unit]
Description=VpnCloud target allowing to start/stop all vpncloud@.service instances at once

View File

@ -2,6 +2,7 @@
Description=VpnCloud network '%I'
After=network-online.target
Wants=network-online.target
PartOf=vpncloud.target
Documentation=man:vpncloud(1)
[Service]

77
benches/.code.rs Normal file
View File

@ -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");
}
}

204
benches/criterion.rs Normal file
View File

@ -0,0 +1,204 @@
#![allow(dead_code, unused_macros, unused_imports)]
#[macro_use] extern crate serde;
#[macro_use] extern crate log;
use criterion::{criterion_group, criterion_main, Criterion, Throughput};
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 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 tests::common::{TunSimulator, TapSimulator};
fn udp_send(c: &mut Criterion) {
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);
let mut g = c.benchmark_group("udp_send");
g.throughput(Throughput::Bytes(1400));
g.bench_function("udp_send", |b| {
b.iter(|| sock.send_to(&data, addr).unwrap());
});
g.finish();
}
fn decode_ipv4(c: &mut Criterion) {
let data = [0x40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 168, 1, 1, 192, 168, 1, 2];
let mut g = c.benchmark_group("payload");
g.throughput(Throughput::Bytes(1400));
g.bench_function("decode_ipv4", |b| {
b.iter(|| Packet::parse(&data).unwrap());
});
g.finish();
}
fn decode_ipv6(c: &mut Criterion) {
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
];
let mut g = c.benchmark_group("payload");
g.throughput(Throughput::Bytes(1400));
g.bench_function("decode_ipv6", |b| {
b.iter(|| Packet::parse(&data).unwrap());
});
g.finish();
}
fn decode_ethernet(c: &mut Criterion) {
let data = [6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 8];
let mut g = c.benchmark_group("payload");
g.throughput(Throughput::Bytes(1400));
g.bench_function("decode_ethernet", |b| {
b.iter(|| Frame::parse(&data).unwrap());
});
g.finish();
}
fn decode_ethernet_with_vlan(c: &mut Criterion) {
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];
let mut g = c.benchmark_group("payload");
g.throughput(Throughput::Bytes(1400));
g.bench_function("decode_ethernet_with_vlan", |b| {
b.iter(|| Frame::parse(&data).unwrap());
});
g.finish();
}
fn lookup_warm(c: &mut Criterion) {
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());
let mut g = c.benchmark_group("table");
g.throughput(Throughput::Bytes(1400));
g.bench_function("lookup_warm", |b| {
b.iter(|| table.lookup(addr));
});
g.finish();
}
fn lookup_cold(c: &mut Criterion) {
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()]);
let mut g = c.benchmark_group("table");
g.throughput(Throughput::Bytes(1400));
g.bench_function("lookup_cold", |b| {
b.iter(|| {
table.clear_cache();
table.lookup(addr)
});
});
g.finish();
}
fn crypto_bench(c: &mut Criterion, algo: &'static aead::Algorithm) {
let mut buffer = MsgBuffer::new(EXTRA_LEN);
buffer.set_length(1400);
let (mut sender, mut receiver) = create_dummy_pair(algo);
let mut g = c.benchmark_group("crypto");
g.throughput(Throughput::Bytes(2*1400));
g.bench_function(format!("{:?}", algo), |b| {
b.iter(|| {
sender.encrypt(&mut buffer);
receiver.decrypt(&mut buffer).unwrap();
});
});
g.finish()
}
fn crypto_chacha20(c: &mut Criterion) {
crypto_bench(c, &aead::CHACHA20_POLY1305)
}
fn crypto_aes128(c: &mut Criterion) {
crypto_bench(c, &aead::AES_128_GCM)
}
fn crypto_aes256(c: &mut Criterion) {
crypto_bench(c, &aead::AES_256_GCM)
}
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);

155
benches/valgrind.rs Normal file
View File

@ -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
);

View File

@ -1,28 +0,0 @@
// VpnCloud - Peer-to-Peer VPN
// Copyright (C) 2015-2020 Dennis Schwerdel
// This software is licensed under GPL-3 or newer (see LICENSE.md)
use std::{env, fs, path::Path, process::Command};
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
// Process manpage using asciidoctor command
println!("cargo:rerun-if-changed=vpncloud.adoc");
fs::create_dir_all(&out_dir).unwrap();
fs::copy("vpncloud.adoc", Path::new(&out_dir).join("vpncloud.adoc")).unwrap();
match Command::new("asciidoctor")
.args(&["-b", "manpage", "vpncloud.adoc"])
.current_dir(&Path::new(&out_dir))
.status()
{
Ok(_) => {
Command::new("gzip").args(&["vpncloud.1"]).current_dir(&Path::new(&out_dir)).status().unwrap();
fs::copy(Path::new(&out_dir).join("vpncloud.1.gz"), "target/vpncloud.1.gz").unwrap();
}
Err(err) => {
println!("cargo:warning=Error building manpage: {}", err);
println!("cargo:warning=The manpage will not be build. Do you have 'asciidoctor'?");
}
}
}

View File

@ -1,2 +0,0 @@
cache
build.sh

View File

@ -1,38 +0,0 @@
FROM ubuntu:16.04
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
build-essential \
curl \
gcc-aarch64-linux-gnu \
gcc-arm-linux-gnueabihf \
libc6-dev-arm64-cross \
libc6-dev-armhf-cross \
libc6-dev-i386 \
gcc-5-multilib \
asciidoctor \
&& rm -rf /var/cache/dpkg
RUN ln -s asm-generic/ /usr/include/asm
RUN useradd -ms /bin/bash user
USER user
WORKDIR /home/user
ENV RUST=1.47.0
RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain ${RUST}
ENV PATH=/home/user/.cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
RUN rustup target add i686-unknown-linux-gnu \
&& rustup target add armv7-unknown-linux-gnueabihf \
&& rustup target add aarch64-unknown-linux-gnu
RUN cargo install cargo-deb \
&& rm -rf /home/user/.cargo/{git,tmp,registry}
VOLUME /home/user/.cargo/tmp
VOLUME /home/user/.cargo/git
VOLUME /home/user/.cargo/registry

View File

@ -1,25 +0,0 @@
FROM centos:7
RUN yum groupinstall -y 'Development Tools'
RUN yum install -y ruby && gem install asciidoctor
RUN useradd -ms /bin/bash user
USER user
WORKDIR /home/user
ENV RUST=1.47.0
RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain ${RUST}
ENV PATH=/home/user/.cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
RUN rustup target add i686-unknown-linux-gnu \
&& rustup target add armv7-unknown-linux-gnueabihf
RUN cargo install cargo-rpm \
&& rm -rf /home/user/.cargo/{git,tmp,registry}
VOLUME /home/user/.cargo/tmp
VOLUME /home/user/.cargo/git
VOLUME /home/user/.cargo/registry

View File

@ -1,55 +0,0 @@
#!/bin/bash
function docker_cmd() {
DIST=$1
CMD=$2
mkdir -p $CACHE/$DIST/{target,registry,git,tmp}
docker run -it --rm -v $(pwd)/..:/home/user/code \
-v $CACHE/$DIST/target:/home/user/code/target \
-v $CACHE/$DIST/registry:/home/user/.cargo/registry \
-v $CACHE/$DIST/git:/home/user/.cargo/git \
-v $CACHE/$DIST/tmp:/home/user/.cargo/tmp \
vpncloud-builder-$DIST bash -c "$CMD"
}
set -e
cd $(dirname $0)
VERSION=$(grep -e '^version =' ../Cargo.toml | sed -e 's/version = "\(.*\)"/\1/')
DEB_VERSION=$(echo "$VERSION" | sed -e 's/-/~/g')
if echo "$VERSION" | fgrep -q "-"; then
RPM_VERSION=$(echo "$VERSION" | sed -e 's/-/-0./g')
else
RPM_VERSION="$VERSION-1"
fi
mkdir -p cache/{rpm,deb}
CACHE=$(pwd)/cache
mkdir -p ../dist
docker build --rm -f=Dockerfile-deb -t vpncloud-builder-deb .
# x86_64 deb
docker_cmd deb 'cd code && cargo deb'
cp $CACHE/deb/target/debian/vpncloud_${DEB_VERSION}_amd64.deb ../dist/vpncloud_${DEB_VERSION}_amd64.deb
# i386 deb
docker_cmd deb 'cd code && cargo deb --target i686-unknown-linux-gnu'
cp $CACHE/deb/target/i686-unknown-linux-gnu/debian/vpncloud_${DEB_VERSION}_i386.deb ../dist/vpncloud_${DEB_VERSION}_i386.deb
# arm7hf deb
docker_cmd deb 'cd code && cargo deb --target armv7-unknown-linux-gnueabihf'
cp $CACHE/deb/target/armv7-unknown-linux-gnueabihf/debian/vpncloud_${DEB_VERSION}_armhf.deb ../dist/vpncloud_${DEB_VERSION}_armhf.deb
# aarch64 deb
docker_cmd deb 'cd code && cargo deb --target aarch64-unknown-linux-gnu'
cp $CACHE/deb/target/aarch64-unknown-linux-gnu/debian/vpncloud_${DEB_VERSION}_arm64.deb ../dist/vpncloud_${DEB_VERSION}_arm64.deb
docker build --rm -f=Dockerfile-rpm -t vpncloud-builder-rpm .
# x86_64 rpm
docker_cmd rpm 'cd code && cargo rpm build'
cp $CACHE/rpm/target/release/rpmbuild/RPMS/x86_64/vpncloud-${RPM_VERSION}.x86_64.rpm ../dist/vpncloud_${RPM_VERSION}.x86_64.rpm

View File

@ -0,0 +1,13 @@
FROM ubuntu
RUN apt-get update && apt-get install -y asciinema locales bash iputils-ping
RUN sed -i '/en_US.UTF-8/s/^# //g' /etc/locale.gen && locale-gen
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8
RUN mkdir /root/.asciinema
RUN mkdir /etc/vpncloud
WORKDIR /data
ADD config /root/.asciinema/config
RUN echo 'PS1="\[\e[00;34m\]\[\e[01;31m\]\u\[\e[00;01;34m\]@\[\e[00;34m\]node\[\e[01;31m\]:\[\e[00;34m\]\w\[\e[01;31m\]> \[\e[00m\]"' >> /root/.bashrc

View File

@ -0,0 +1,3 @@
[record]
command = bash -l
idle_time_limit = 2.5

View File

@ -0,0 +1,11 @@
#!/bin/bash
set -e
cd $(dirname $0)
docker build -t asciinema-recorder .
docker run -it --rm --network host \
-v $(pwd):/data \
-v /etc/hosts:/etc/hosts \
asciinema-recorder

View File

@ -0,0 +1,81 @@
AWSTemplateFormatVersion: 2010-09-09
Description: |
VpnCloud Websocket Proxy
This will configure a websocket proxy to be used with VpnCloud.
Versions: Ubuntu Server 20.04 LTS + VpnCloud 2.1.0
Parameters:
LatestAmiId:
Description: "Image to use (just leave this as it is)"
Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
Default: '/aws/service/canonical/ubuntu/server/20.04/stable/current/arm64/hvm/ebs-gp2/ami-id'
AllowedValues:
- '/aws/service/canonical/ubuntu/server/20.04/stable/current/arm64/hvm/ebs-gp2/ami-id'
Resources:
ProxySecurityGroup:
Type: 'AWS::EC2::SecurityGroup'
Properties:
GroupDescription: Enable HTTP access via port 80 and any UDP port
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: '80'
ToPort: '80'
CidrIp: 0.0.0.0/0
- IpProtocol: udp
FromPort: '1024'
ToPort: '65535'
CidrIp: 0.0.0.0/0
LaunchTemplate:
Type: AWS::EC2::LaunchTemplate
DependsOn:
- ProxySecurityGroup
Properties:
LaunchTemplateData:
ImageId: !Ref LatestAmiId
SecurityGroups:
- !Ref ProxySecurityGroup
InstanceMarketOptions:
MarketType: spot
InstanceType: t4g.nano
TagSpecifications:
- ResourceType: instance
Tags:
- Key: Name
Value: VpnCloud WS Proxy
CreditSpecification:
CpuCredits: standard
BlockDeviceMappings:
- DeviceName: /dev/sda1
Ebs:
VolumeType: standard
VolumeSize: '8'
DeleteOnTermination: 'true'
Encrypted: 'false'
UserData:
Fn::Base64: !Sub |
#cloud-config
packages:
- iperf3
- socat
runcmd:
- wget https://github.com/dswd/vpncloud/releases/download/v2.1.0/vpncloud_2.1.0_arm64.deb -O /tmp/vpncloud.deb
- dpkg -i /tmp/vpncloud.deb
- nohup vpncloud ws-proxy -l 80 &
ProxyInstance:
Type: 'AWS::EC2::Instance'
DependsOn:
- LaunchTemplate
Properties:
LaunchTemplate:
LaunchTemplateId:
Ref: LaunchTemplate
Version: 1
Outputs:
ProxyURL:
Description: URL to use in VpnCloud config
Value: !Join
- ''
- - 'ws://'
- !GetAtt
- ProxyInstance
- PublicDnsName
- ':80'

View File

@ -120,7 +120,7 @@ def find_ami(region, owner, name_pattern, arch='x86_64'):
class EC2Environment:
def __init__(self, vpncloud_version, region, node_count, instance_type, vpncloud_file=None, use_spot=True, max_price=0.1, ami=('amazon', 'amzn2-ami-hvm-*'), username="ec2-user", subnet=CREATE, keyname=CREATE, privatekey=CREATE, tag="vpncloud", cluster_nodes=False):
def __init__(self, vpncloud_version, region, node_count, instance_type, vpncloud_file=None, use_spot=True, max_price=0.1, ami=('amazon', 'al2023-ami-*-hvm-*'), username="ec2-user", subnet=CREATE, keyname=CREATE, privatekey=CREATE, tag="vpncloud", cluster_nodes=False):
self.region = region
self.node_count = node_count
self.instance_type = instance_type
@ -249,7 +249,6 @@ runcmd:
"Ebs": {
"DeleteOnTermination": True,
"VolumeType": "gp2",
"VolumeSize": 8,
}
}
],
@ -292,7 +291,7 @@ runcmd:
MinCount=self.node_count,
NetworkInterfaces=[
{
'SubnetId': self.subnet.id,
'SubnetId': self.subnet,
'DeviceIndex': 0,
'AssociatePublicIpAddress': True,
'Groups': [sg.group_id]
@ -300,7 +299,7 @@ runcmd:
],
Placement=placement,
UserData=userdata,
KeyName='vpncloud-perf-test-keypair'
KeyName=key_pair.name
)
for instance in self.instances:
self.track_resource(instance)

View File

@ -6,8 +6,8 @@ import time
setup = EC2Environment(
region = "eu-central-1",
node_count = 2,
instance_type = 't3.nano',
vpncloud_version = "1.4.0"
instance_type = 't3a.nano',
vpncloud_version = "2.1.0"
)
sender = setup.nodes[0]

View File

@ -0,0 +1,165 @@
{
"meta": {
"region": "eu-central-1",
"instance_type": "m5.large",
"ami": "ami-0a6dc7529cd559185",
"version": "2.1.0",
"duration": 622.053159236908
},
"native": {
"iperf": {
"throughput": 9672965000.0,
"cpu_sender": 11.936759,
"cpu_receiver": 70.348812
},
"ping_100": {
"rtt_min": 0.046,
"rtt_max": 0.246,
"rtt_avg": 0.053,
"pkt_loss": 0.0
},
"ping_500": {
"rtt_min": 0.048,
"rtt_max": 0.183,
"rtt_avg": 0.055,
"pkt_loss": 0.0
},
"ping_1000": {
"rtt_min": 0.05,
"rtt_max": 0.272,
"rtt_avg": 0.057,
"pkt_loss": 0.0
}
},
"plain": {
"iperf": {
"throughput": 5728527000.0,
"cpu_sender": 11.004746,
"cpu_receiver": 67.527328
},
"ping_100": {
"rtt_min": 0.078,
"rtt_max": 0.372,
"rtt_avg": 0.095,
"pkt_loss": 0.0
},
"ping_500": {
"rtt_min": 0.078,
"rtt_max": 0.272,
"rtt_avg": 0.094,
"pkt_loss": 0.0
},
"ping_1000": {
"rtt_min": 0.082,
"rtt_max": 0.217,
"rtt_avg": 0.096,
"pkt_loss": 0.0
}
},
"aes256": {
"iperf": {
"throughput": 3706944000.0,
"cpu_sender": 6.465523,
"cpu_receiver": 60.216674
},
"ping_100": {
"rtt_min": 0.079,
"rtt_max": 0.28,
"rtt_avg": 0.097,
"pkt_loss": 0.0
},
"ping_500": {
"rtt_min": 0.079,
"rtt_max": 13.372,
"rtt_avg": 0.099,
"pkt_loss": 0.0
},
"ping_1000": {
"rtt_min": 0.086,
"rtt_max": 0.358,
"rtt_avg": 0.102,
"pkt_loss": 0.0
}
},
"aes128": {
"iperf": {
"throughput": 3876646000.0,
"cpu_sender": 6.800352,
"cpu_receiver": 61.738244
},
"ping_100": {
"rtt_min": 0.078,
"rtt_max": 0.219,
"rtt_avg": 0.096,
"pkt_loss": 0.0
},
"ping_500": {
"rtt_min": 0.083,
"rtt_max": 0.232,
"rtt_avg": 0.097,
"pkt_loss": 0.0
},
"ping_1000": {
"rtt_min": 0.087,
"rtt_max": 0.327,
"rtt_avg": 0.099,
"pkt_loss": 0.0
}
},
"chacha20": {
"iperf": {
"throughput": 2917879000.0,
"cpu_sender": 5.066722,
"cpu_receiver": 55.171241
},
"ping_100": {
"rtt_min": 0.081,
"rtt_max": 0.283,
"rtt_avg": 0.097,
"pkt_loss": 0.0
},
"ping_500": {
"rtt_min": 0.087,
"rtt_max": 0.348,
"rtt_avg": 0.103,
"pkt_loss": 0.0
},
"ping_1000": {
"rtt_min": 0.088,
"rtt_max": 0.309,
"rtt_avg": 0.105,
"pkt_loss": 0.0
}
},
"results": {
"throughput_mbits": {
"native": 9672.965,
"plain": 5728.527,
"aes256": 3706.944,
"aes128": 3876.646,
"chacha20": 2917.879
},
"latency_us": {
"plain": {
"100": 21.0,
"500": 19.5,
"1000": 19.5
},
"aes256": {
"100": 22.000000000000004,
"500": 22.000000000000004,
"1000": 22.499999999999996
},
"aes128": {
"100": 21.5,
"500": 21.0,
"1000": 21.0
},
"chacha20": {
"100": 22.000000000000004,
"500": 23.999999999999996,
"1000": 23.999999999999996
}
}
}
}

View File

@ -0,0 +1,165 @@
{
"meta": {
"region": "eu-central-1",
"instance_type": "m5.large",
"ami": "ami-0db9040eb3ab74509",
"version": "2.2.0",
"duration": 623.0307722091675
},
"native": {
"iperf": {
"throughput": 9680235000.0,
"cpu_sender": 12.015535,
"cpu_receiver": 71.982452
},
"ping_100": {
"rtt_min": 0.049,
"rtt_max": 0.219,
"rtt_avg": 0.058,
"pkt_loss": 0.0
},
"ping_500": {
"rtt_min": 0.053,
"rtt_max": 0.247,
"rtt_avg": 0.059,
"pkt_loss": 0.0
},
"ping_1000": {
"rtt_min": 0.053,
"rtt_max": 0.189,
"rtt_avg": 0.06,
"pkt_loss": 0.0
}
},
"plain": {
"iperf": {
"throughput": 5790600000.0,
"cpu_sender": 14.109763,
"cpu_receiver": 69.727033
},
"ping_100": {
"rtt_min": 0.079,
"rtt_max": 0.291,
"rtt_avg": 0.094,
"pkt_loss": 0.0
},
"ping_500": {
"rtt_min": 0.079,
"rtt_max": 0.304,
"rtt_avg": 0.096,
"pkt_loss": 0.0
},
"ping_1000": {
"rtt_min": 0.082,
"rtt_max": 0.367,
"rtt_avg": 0.097,
"pkt_loss": 0.0
}
},
"aes256": {
"iperf": {
"throughput": 3917767000.0,
"cpu_sender": 6.439156,
"cpu_receiver": 64.267206
},
"ping_100": {
"rtt_min": 0.081,
"rtt_max": 0.206,
"rtt_avg": 0.097,
"pkt_loss": 0.0
},
"ping_500": {
"rtt_min": 0.088,
"rtt_max": 0.206,
"rtt_avg": 0.1,
"pkt_loss": 0.0
},
"ping_1000": {
"rtt_min": 0.089,
"rtt_max": 0.319,
"rtt_avg": 0.103,
"pkt_loss": 0.0
}
},
"aes128": {
"iperf": {
"throughput": 3697142000.0,
"cpu_sender": 7.417808,
"cpu_receiver": 59.433831
},
"ping_100": {
"rtt_min": 0.083,
"rtt_max": 0.265,
"rtt_avg": 0.097,
"pkt_loss": 0.0
},
"ping_500": {
"rtt_min": 0.081,
"rtt_max": 0.369,
"rtt_avg": 0.102,
"pkt_loss": 0.0
},
"ping_1000": {
"rtt_min": 0.086,
"rtt_max": 0.448,
"rtt_avg": 0.102,
"pkt_loss": 0.0
}
},
"chacha20": {
"iperf": {
"throughput": 3194412000.0,
"cpu_sender": 6.12856,
"cpu_receiver": 61.223349
},
"ping_100": {
"rtt_min": 0.081,
"rtt_max": 0.28,
"rtt_avg": 0.098,
"pkt_loss": 0.0
},
"ping_500": {
"rtt_min": 0.088,
"rtt_max": 0.264,
"rtt_avg": 0.103,
"pkt_loss": 0.0
},
"ping_1000": {
"rtt_min": 0.092,
"rtt_max": 0.204,
"rtt_avg": 0.106,
"pkt_loss": 0.0
}
},
"results": {
"throughput_mbits": {
"native": 9680.235,
"plain": 5790.6,
"aes256": 3917.767,
"aes128": 3697.142,
"chacha20": 3194.412
},
"latency_us": {
"plain": {
"100": 18.0,
"500": 18.500000000000004,
"1000": 18.500000000000004
},
"aes256": {
"100": 19.5,
"500": 20.500000000000004,
"1000": 21.5
},
"aes128": {
"100": 19.5,
"500": 21.5,
"1000": 20.999999999999996
},
"chacha20": {
"100": 20.0,
"500": 22.0,
"1000": 23.0
}
}
}
}

View File

@ -0,0 +1,165 @@
{
"meta": {
"region": "eu-central-1",
"instance_type": "m5.large",
"ami": "ami-099ccc441b2ef41ec",
"version": "2.3.0",
"duration": 622.5463161468506
},
"native": {
"iperf": {
"throughput": 9529265000.0,
"cpu_sender": 11.32918,
"cpu_receiver": 61.870429
},
"ping_100": {
"rtt_min": 0.046,
"rtt_max": 0.225,
"rtt_avg": 0.053,
"pkt_loss": 0.0
},
"ping_500": {
"rtt_min": 0.047,
"rtt_max": 10.98,
"rtt_avg": 0.054,
"pkt_loss": 0.0
},
"ping_1000": {
"rtt_min": 0.048,
"rtt_max": 0.175,
"rtt_avg": 0.056,
"pkt_loss": 0.0
}
},
"plain": {
"iperf": {
"throughput": 6388312000.0,
"cpu_sender": 16.955082,
"cpu_receiver": 72.705695
},
"ping_100": {
"rtt_min": 0.076,
"rtt_max": 11.973,
"rtt_avg": 0.09,
"pkt_loss": 0.0
},
"ping_500": {
"rtt_min": 0.08,
"rtt_max": 10.95,
"rtt_avg": 0.094,
"pkt_loss": 0.0
},
"ping_1000": {
"rtt_min": 0.081,
"rtt_max": 1.638,
"rtt_avg": 0.095,
"pkt_loss": 0.0
}
},
"aes256": {
"iperf": {
"throughput": 3801851000.0,
"cpu_sender": 5.826756,
"cpu_receiver": 61.612033
},
"ping_100": {
"rtt_min": 0.075,
"rtt_max": 0.9,
"rtt_avg": 0.093,
"pkt_loss": 0.0
},
"ping_500": {
"rtt_min": 0.079,
"rtt_max": 0.275,
"rtt_avg": 0.091,
"pkt_loss": 0.0
},
"ping_1000": {
"rtt_min": 0.08,
"rtt_max": 1.015,
"rtt_avg": 0.093,
"pkt_loss": 0.0
}
},
"aes128": {
"iperf": {
"throughput": 3880325000.0,
"cpu_sender": 6.219277,
"cpu_receiver": 62.125445
},
"ping_100": {
"rtt_min": 0.077,
"rtt_max": 11.656,
"rtt_avg": 0.09,
"pkt_loss": 0.0
},
"ping_500": {
"rtt_min": 0.08,
"rtt_max": 0.211,
"rtt_avg": 0.095,
"pkt_loss": 0.0
},
"ping_1000": {
"rtt_min": 0.082,
"rtt_max": 1.398,
"rtt_avg": 0.095,
"pkt_loss": 0.0
}
},
"chacha20": {
"iperf": {
"throughput": 3126447000.0,
"cpu_sender": 5.113819,
"cpu_receiver": 58.58095
},
"ping_100": {
"rtt_min": 0.079,
"rtt_max": 0.271,
"rtt_avg": 0.091,
"pkt_loss": 0.0
},
"ping_500": {
"rtt_min": 0.083,
"rtt_max": 0.272,
"rtt_avg": 0.098,
"pkt_loss": 0.0
},
"ping_1000": {
"rtt_min": 0.087,
"rtt_max": 1.615,
"rtt_avg": 0.101,
"pkt_loss": 0.0
}
},
"results": {
"throughput_mbits": {
"native": 9529.265,
"plain": 6388.312,
"aes256": 3801.851,
"aes128": 3880.325,
"chacha20": 3126.447
},
"latency_us": {
"plain": {
"100": 18.5,
"500": 20.0,
"1000": 19.5
},
"aes256": {
"100": 20.0,
"500": 18.5,
"1000": 18.5
},
"aes128": {
"100": 18.5,
"500": 20.5,
"1000": 19.5
},
"chacha20": {
"100": 19.0,
"500": 22.000000000000004,
"1000": 22.500000000000004
}
}
}
}

View File

@ -7,15 +7,15 @@ from datetime import date
# Note: this script will run for ~8 minutes and incur costs of about $ 0.02
FILE = "../target/release/vpncloud"
VERSION = "2.0.0-alpha1"
FILE = "../../target/release/vpncloud"
VERSION = "2.4.0"
REGION = "eu-central-1"
env = EC2Environment(
region = REGION,
node_count = 2,
instance_type = "m5.large",
use_spot = True,
use_spot = False,
max_price = "0.08", # USD per hour per VM
vpncloud_version = VERSION,
vpncloud_file = FILE,
@ -113,4 +113,4 @@ name = "measurements/{date}_{version}_perf.json".format(date=date.today().strfti
eprint('Storing results in {}'.format(name))
with open(name, 'w') as fp:
json.dump(results, fp, indent=2)
eprint("done.")
eprint("done.")

View File

@ -5,11 +5,11 @@ import atexit, argparse, os
REGION = "eu-central-1"
VERSION = "2.0.0"
VERSION = "2.1.0"
parser = argparse.ArgumentParser(description='Create a test setup')
parser.add_argument('--instancetype', default='t3.nano', help='EC2 instance type')
parser.add_argument('--instancetype', default='t3a.nano', help='EC2 instance type')
parser.add_argument('--version', default=VERSION, help='VpnCloud version to use')
parser.add_argument('--count', '-c', dest="count", type=int, default=2, help='Number of instance to create')
parser.add_argument('--cluster', action="store_true", help='Cluster instances to get reliable throughput')
@ -25,15 +25,22 @@ if args.keyname:
with open(args.keyfile, 'r') as fp:
privatekey = fp.read()
opts = {}
if os.path.exists(args.version):
opts["vpncloud_file"] = args.version
opts["vpncloud_version"] = None
else:
opts["vpncloud_version"] = args.version
setup = EC2Environment(
region = REGION,
node_count = args.count,
instance_type = args.instancetype,
vpncloud_version = args.version,
cluster_nodes = args.cluster,
subnet = args.subnet or CREATE,
keyname = args.keyname or CREATE,
privatekey = privatekey
privatekey = privatekey,
**opts
)
if not args.keyname:

209
maskfile.md Normal file
View File

@ -0,0 +1,209 @@
# Commands
Needs [mask](https://github.com/jacobdeichert/mask) to run.
## install-tools
> Install tools.
```sh
set -e
apt-get install -y asciidoctor
cargo install cargo-binstall
cargo binstall cross cargo-deb cargo-generate-rpm
UPX_VERSION=$(grep -e '^upx_version =' Cargo.toml | sed -e 's/upx_version = "\(.*\)"/\1/')
curl https://github.com/upx/upx/releases/download/v${UPX_VERSION}/upx-${UPX_VERSION}-amd64_linux.tar.xz -Lf | tar -xJ --strip-components=1 -C /usr/local/bin
```
## manpage
> Generate manpage.
```sh
set -e
echo >&2 "Generating manpage"
if [ ! -f target/vpncloud.1.gz -o vpncloud.adoc -nt target/vpncloud.1.gz ]; then
asciidoctor -b manpage -o target/vpncloud.1 vpncloud.adoc
gzip -f target/vpncloud.1
fi
```
## build-packages-cross (target) (target_name) (target_name_rpm)
> Build the project packages for a given target.
```sh
set -e
VERSION=$(grep -e '^version =' Cargo.toml | sed -e 's/version = "\(.*\)"/\1/')
TARGET=$target
TARGET_DIR=target/$target_name
# compile
echo >&2 "Compiling for $target_name"
cross build --release --target $TARGET --target-dir $TARGET_DIR
mkdir -p target/$TARGET/release
cp $TARGET_DIR/$TARGET/release/vpncloud target/$TARGET/release/
# build deb
echo >&2 "Building deb package"
cargo deb --no-build --no-strip --target $TARGET
mv target/$TARGET/debian/vpncloud_${VERSION}-1_$target_name.deb dist/vpncloud_${VERSION}_$target_name.deb
# build rpm
if [ -n "$target_name_rpm" ]; then
echo >&2 "Building rpm package"
cargo generate-rpm --target $TARGET --target-dir $TARGET_DIR
mv $TARGET_DIR/$TARGET/generate-rpm/vpncloud-${VERSION}-1.$target_name_rpm.rpm dist/vpncloud_${VERSION}-1.$target_name_rpm.rpm
fi
```
## build-amd64-packages
```sh
$MASK build-packages-cross x86_64-unknown-linux-gnu amd64 x86_64
```
## build-i386-packages
```sh
$MASK build-packages-cross i686-unknown-linux-gnu i386 i686
```
## build-arm64-packages
```sh
$MASK build-packages-cross aarch64-unknown-linux-gnu arm64 aarch64
```
## build-armhf-packages
```sh
$MASK build-packages-cross armv7-unknown-linux-gnueabihf armhf ""
```
## build-armel-packages
```sh
$MASK build-packages-cross armv5te-unknown-linux-gnueabi armel ""
```
## build-static-cross (target) (target_name)
> Build the project statically for a given target.
```sh
set -e
VERSION=$(grep -e '^version =' Cargo.toml | sed -e 's/version = "\(.*\)"/\1/')
TARGET=$target
TARGET_DIR=target/$target_name-musl
BIN=$TARGET_DIR/$TARGET/release/vpncloud
echo >&2 "Compiling for $target_name musl"
cross build --release --features installer --target $TARGET --target-dir $TARGET_DIR
upx --lzma $BIN
cp $BIN dist/vpncloud_${VERSION}_static_$target_name
```
## build-amd64-static
```sh
$MASK build-static-cross x86_64-unknown-linux-musl amd64
```
## build-i386-static
```sh
$MASK build-static-cross i686-unknown-linux-musl i386
```
## build-arm64-static
```sh
$MASK build-static-cross aarch64-unknown-linux-musl arm64
```
## build-armhf-static
```sh
$MASK build-static-cross armv7-unknown-linux-musleabihf armhf
```
## build-armel-static
```sh
$MASK build-static-cross armv5te-unknown-linux-musleabi armel
```
## build
> Build the project for all architectures.
```sh
set -e
$MASK manpage
$MASK build-amd64-packages
$MASK build-amd64-static
$MASK build-i386-packages
$MASK build-i386-static
$MASK build-arm64-packages
$MASK build-arm64-static
$MASK build-armhf-packages
$MASK build-armhf-static
$MASK build-armel-packages
$MASK build-armel-static
```
## sign
> Sign the packages.
```sh
set -e
VERSION=$(grep -e '^version =' Cargo.toml | sed -e 's/version = "\(.*\)"/\1/')
cd dist
sha256sum vpncloud_${VERSION}_static_* vpncloud_${VERSION}*.rpm vpncloud_${VERSION}*.deb > vpncloud_${VERSION}_SHA256SUMS.txt
gpg --armor --output vpncloud_${VERSION}_SHA256SUMS.txt.asc --detach-sig vpncloud_${VERSION}_SHA256SUMS.txt
```
## test
> Test the project.
```sh
cargo test --all-features
```
## release
> Release the project.
```sh
set -e
$MASK test
nano Cargo.toml
VERSION=$(grep -e '^version =' Cargo.toml | sed -e 's/version = "\(.*\)"/\1/')
nano CHANGELOG.md
nano assets/changelog.txt
$MASK build
$MASK sign
git commit -a
cargo publish
git tag v$VERSION
git push --tags
```
## count
> Count the lines of code.
```sh
tokei
```

View File

@ -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;
@ -15,16 +15,15 @@ use std::{
process::{Command, Stdio},
sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex
Arc, Mutex,
},
thread
thread,
};
use super::util::{from_base62, to_base62, Encoder, TimeSource};
use smallvec::SmallVec;
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
const TYPE_BEGIN: u8 = 0;
const TYPE_END: u8 = 1;
const TYPE_DATA: u8 = 2;
@ -40,14 +39,14 @@ fn sha512(data: &[u8]) -> SmallVec<[u8; 64]> {
struct FutureResult<T> {
has_result: AtomicBool,
result: Mutex<T>
result: Mutex<T>,
}
#[derive(Clone)]
pub struct BeaconSerializer<TS> {
shared_key: Vec<u8>,
future_peers: Arc<FutureResult<Vec<SocketAddr>>>,
_dummy_ts: PhantomData<TS>
_dummy_ts: PhantomData<TS>,
}
impl<TS: TimeSource> BeaconSerializer<TS> {
@ -55,7 +54,7 @@ impl<TS: TimeSource> BeaconSerializer<TS> {
Self {
shared_key: shared_key.to_owned(),
future_peers: Arc::new(FutureResult { has_result: AtomicBool::new(false), result: Mutex::new(Vec::new()) }),
_dummy_ts: PhantomData
_dummy_ts: PhantomData,
}
}
@ -105,7 +104,7 @@ impl<TS: TimeSource> BeaconSerializer<TS> {
fn decrypt_data(&self, data: &mut Vec<u8>) -> bool {
if data.is_empty() {
return false
return false;
}
let seed = data.pop().unwrap() ^ self.get_keystream(TYPE_SEED, 0, 0)[0];
self.mask_with_keystream(data as &mut [u8], TYPE_DATA, seed);
@ -122,7 +121,7 @@ impl<TS: TimeSource> BeaconSerializer<TS> {
for p in peers {
match *p {
SocketAddr::V4(addr) => v4addrs.push(addr),
SocketAddr::V6(addr) => v6addrs.push(addr)
SocketAddr::V6(addr) => v6addrs.push(addr),
}
}
// Add count of v4 addresses
@ -158,23 +157,23 @@ impl<TS: TimeSource> BeaconSerializer<TS> {
let mut peers = Vec::new();
let mut pos = 0;
if data.len() < 4 {
return peers
return peers;
}
if !self.decrypt_data(&mut data) {
return peers
return peers;
}
let then = Wrapping(Encoder::read_u16(&data[pos..=pos + 1]));
if let Some(ttl) = ttl_hours {
let now = Wrapping(Self::now_hour_16());
if now - then > Wrapping(ttl) && then - now > Wrapping(ttl) {
return peers
return peers;
}
}
pos += 2;
let v4count = data[pos] as usize;
pos += 1;
if v4count * 6 > data.len() - pos || (data.len() - pos - v4count * 6) % 18 > 0 {
return peers
return peers;
}
for _ in 0..v4count {
assert!(data.len() >= pos + 6);
@ -198,7 +197,7 @@ impl<TS: TimeSource> BeaconSerializer<TS> {
Ipv6Addr::new(ip[0], ip[1], ip[2], ip[3], ip[4], ip[5], ip[6], ip[7]),
port,
0,
0
0,
));
peers.push(addr);
}
@ -229,7 +228,7 @@ impl<TS: TimeSource> BeaconSerializer<TS> {
let beacon = format!("{}{}{}", begin, data, end);
debug!("Calling beacon command: {}", cmd);
let process = Command::new("sh")
.args(&["-c", cmd])
.args(["-c", cmd])
.env("begin", begin)
.env("data", data)
.env("end", end)
@ -262,14 +261,14 @@ impl<TS: TimeSource> BeaconSerializer<TS> {
peers.append(&mut self.peerlist_decode(&data[start_pos..end_pos], ttl_hours));
pos = start_pos
} else {
break
break;
}
}
peers
}
pub fn read_from_file<P: AsRef<Path>>(
&self, path: P, ttl_hours: Option<u16>
&self, path: P, ttl_hours: Option<u16>,
) -> Result<Vec<SocketAddr>, io::Error> {
let mut f = File::open(&path)?;
let mut contents = String::new();
@ -282,7 +281,7 @@ impl<TS: TimeSource> BeaconSerializer<TS> {
let end = self.end();
debug!("Calling beacon command: {}", cmd);
let process = Command::new("sh")
.args(&["-c", cmd])
.args(["-c", cmd])
.env("begin", begin)
.env("end", end)
.stdout(Stdio::piped())
@ -316,24 +315,22 @@ impl<TS: TimeSource> BeaconSerializer<TS> {
}
}
#[cfg(test)] use crate::util::MockTimeSource;
#[cfg(test)] use std::str::FromStr;
#[cfg(test)] use std::time::Duration;
#[cfg(test)]
use crate::util::MockTimeSource;
#[cfg(test)]
use std::str::FromStr;
#[cfg(test)]
use std::time::Duration;
#[test]
fn encode() {
MockTimeSource::set_time(2000 * 3600);
let ser = BeaconSerializer::<MockTimeSource>::new(b"mysecretkey");
let mut peers = Vec::new();
peers.push(SocketAddr::from_str("1.2.3.4:5678").unwrap());
peers.push(SocketAddr::from_str("6.6.6.6:53").unwrap());
let mut peers = vec![SocketAddr::from_str("1.2.3.4:5678").unwrap(), SocketAddr::from_str("6.6.6.6:53").unwrap()];
assert_eq!("WsHI31EWDMBYxvITiILIrm2k9gEik22E", ser.encode(&peers));
peers.push(SocketAddr::from_str("[::1]:5678").unwrap());
assert_eq!("WsHI3GXKaXCveo6uejmZizZ72kR6Y0L9T7h49TXONp1ugfKvvvEik22E", ser.encode(&peers));
let mut peers = Vec::new();
peers.push(SocketAddr::from_str("1.2.3.4:5678").unwrap());
peers.push(SocketAddr::from_str("6.6.6.6:54").unwrap());
let peers = vec![SocketAddr::from_str("1.2.3.4:5678").unwrap(), SocketAddr::from_str("6.6.6.6:54").unwrap()];
assert_eq!("WsHI32gm9eMSHP3Lm1GXcdP7rD3ik22E", ser.encode(&peers));
}
@ -341,9 +338,7 @@ fn encode() {
fn decode() {
MockTimeSource::set_time(2000 * 3600);
let ser = BeaconSerializer::<MockTimeSource>::new(b"mysecretkey");
let mut peers = Vec::new();
peers.push(SocketAddr::from_str("1.2.3.4:5678").unwrap());
peers.push(SocketAddr::from_str("6.6.6.6:53").unwrap());
let mut peers = vec![SocketAddr::from_str("1.2.3.4:5678").unwrap(), SocketAddr::from_str("6.6.6.6:53").unwrap()];
assert_eq!(format!("{:?}", peers), format!("{:?}", ser.decode("WsHI31EWDMBYxvITiILIrm2k9gEik22E", None)));
peers.push(SocketAddr::from_str("[::1]:5678").unwrap());
assert_eq!(
@ -356,9 +351,7 @@ fn decode() {
fn decode_split() {
MockTimeSource::set_time(2000 * 3600);
let ser = BeaconSerializer::<MockTimeSource>::new(b"mysecretkey");
let mut peers = Vec::new();
peers.push(SocketAddr::from_str("1.2.3.4:5678").unwrap());
peers.push(SocketAddr::from_str("6.6.6.6:53").unwrap());
let peers = vec![SocketAddr::from_str("1.2.3.4:5678").unwrap(), SocketAddr::from_str("6.6.6.6:53").unwrap()];
assert_eq!(
format!("{:?}", peers),
format!("{:?}", ser.decode("WsHI3-1E.WD:MB Yx\tvI\nTi(IL)Ir[m2]k9ügEäik22E", None))
@ -373,9 +366,7 @@ fn decode_split() {
fn decode_offset() {
MockTimeSource::set_time(2000 * 3600);
let ser = BeaconSerializer::<MockTimeSource>::new(b"mysecretkey");
let mut peers = Vec::new();
peers.push(SocketAddr::from_str("1.2.3.4:5678").unwrap());
peers.push(SocketAddr::from_str("6.6.6.6:53").unwrap());
let peers = vec![SocketAddr::from_str("1.2.3.4:5678").unwrap(), SocketAddr::from_str("6.6.6.6:53").unwrap()];
assert_eq!(
format!("{:?}", peers),
format!("{:?}", ser.decode("Hello World: WsHI31EWDMBYxvITiILIrm2k9gEik22E! End of the World", None))
@ -386,9 +377,7 @@ fn decode_offset() {
fn decode_multiple() {
MockTimeSource::set_time(2000 * 3600);
let ser = BeaconSerializer::<MockTimeSource>::new(b"mysecretkey");
let mut peers = Vec::new();
peers.push(SocketAddr::from_str("1.2.3.4:5678").unwrap());
peers.push(SocketAddr::from_str("6.6.6.6:53").unwrap());
let peers = vec![SocketAddr::from_str("1.2.3.4:5678").unwrap(), SocketAddr::from_str("6.6.6.6:53").unwrap()];
assert_eq!(
format!("{:?}", peers),
format!("{:?}", ser.decode("WsHI31HVpqxFNMNSPrvik22E WsHI34yOBcZIulKdtn2ik22E", None))
@ -399,9 +388,6 @@ fn decode_multiple() {
fn decode_ttl() {
MockTimeSource::set_time(2000 * 3600);
let ser = BeaconSerializer::<MockTimeSource>::new(b"mysecretkey");
let mut peers = Vec::new();
peers.push(SocketAddr::from_str("1.2.3.4:5678").unwrap());
peers.push(SocketAddr::from_str("6.6.6.6:53").unwrap());
MockTimeSource::set_time(2000 * 3600);
assert_eq!(2, ser.decode("WsHI31EWDMBYxvITiILIrm2k9gEik22E", None).len());
MockTimeSource::set_time(2100 * 3600);
@ -435,14 +421,11 @@ fn decode_invalid() {
assert_eq!(2, ser.decode("WsHI3WsHI31EWDMBYxvITiILIrm2k9gEik22Eik22E", None).len());
}
#[test]
fn encode_decode() {
MockTimeSource::set_time(2000 * 3600);
let ser = BeaconSerializer::<MockTimeSource>::new(b"mysecretkey");
let mut peers = Vec::new();
peers.push(SocketAddr::from_str("1.2.3.4:5678").unwrap());
peers.push(SocketAddr::from_str("6.6.6.6:53").unwrap());
let peers = vec![SocketAddr::from_str("1.2.3.4:5678").unwrap(), SocketAddr::from_str("6.6.6.6:53").unwrap()];
let data = ser.encode(&peers);
let peers2 = ser.decode(&data, None);
assert_eq!(format!("{:?}", peers), format!("{:?}", peers2));
@ -452,9 +435,7 @@ fn encode_decode() {
fn encode_decode_file() {
MockTimeSource::set_time(2000 * 3600);
let ser = BeaconSerializer::<MockTimeSource>::new(b"mysecretkey");
let mut peers = Vec::new();
peers.push(SocketAddr::from_str("1.2.3.4:5678").unwrap());
peers.push(SocketAddr::from_str("6.6.6.6:53").unwrap());
let peers = vec![SocketAddr::from_str("1.2.3.4:5678").unwrap(), SocketAddr::from_str("6.6.6.6:53").unwrap()];
let file = tempfile::NamedTempFile::new().expect("Failed to create temp file");
assert!(ser.write_to_file(&peers, file.path()).is_ok());
let peers2 = ser.read_from_file(file.path(), None);
@ -466,9 +447,7 @@ fn encode_decode_file() {
fn encode_decode_cmd() {
MockTimeSource::set_time(2000 * 3600);
let ser = BeaconSerializer::<MockTimeSource>::new(b"mysecretkey");
let mut peers = Vec::new();
peers.push(SocketAddr::from_str("1.2.3.4:5678").unwrap());
peers.push(SocketAddr::from_str("6.6.6.6:53").unwrap());
let peers = vec![SocketAddr::from_str("1.2.3.4:5678").unwrap(), SocketAddr::from_str("6.6.6.6:53").unwrap()];
let file = tempfile::NamedTempFile::new().expect("Failed to create temp file");
assert!(ser.write_to_cmd(&peers, &format!("echo $beacon > {}", file.path().display())).is_ok());
thread::sleep(Duration::from_millis(100));

View File

@ -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::{
@ -12,7 +12,7 @@ use std::{
marker::PhantomData,
net::{SocketAddr, ToSocketAddrs},
path::Path,
str::FromStr
str::FromStr,
};
use fnv::FnvHasher;
@ -26,16 +26,17 @@ use crate::{
device::{Device, Type},
error::Error,
messages::{
NodeInfo, PeerInfo, MESSAGE_TYPE_CLOSE, MESSAGE_TYPE_DATA, MESSAGE_TYPE_KEEPALIVE, MESSAGE_TYPE_NODE_INFO
AddrList, NodeInfo, PeerInfo, MESSAGE_TYPE_CLOSE, MESSAGE_TYPE_DATA, MESSAGE_TYPE_KEEPALIVE,
MESSAGE_TYPE_NODE_INFO,
},
net::{mapped_addr, Socket},
net::{mapped_addr, parse_listen, Socket},
payload::Protocol,
poll::{WaitImpl, WaitResult},
port_forwarding::PortForwarding,
table::ClaimTable,
traffic::TrafficStats,
types::{Address, Mode, NodeId, Range, RangeList},
util::{addr_nice, resolve, CtrlC, Duration, MsgBuffer, StatsdMsg, Time, TimeSource}
util::{addr_nice, bytes_to_hex, resolve, CtrlC, Duration, MsgBuffer, StatsdMsg, Time, TimeSource},
};
pub type Hash = BuildHasherDefault<FnvHasher>;
@ -47,24 +48,25 @@ const OWN_ADDRESS_RESET_INTERVAL: Time = 300;
const SPACE_BEFORE: usize = 100;
struct PeerData {
addrs: AddrList,
#[allow(dead_code)] //TODO: export in status
last_seen: Time,
timeout: Time,
peer_timeout: u16,
node_id: NodeId,
crypto: PeerCrypto<NodeInfo>
crypto: PeerCrypto<NodeInfo>,
}
#[derive(Clone)]
pub struct ReconnectEntry {
address: Option<(String, Time)>,
resolved: SmallVec<[SocketAddr; 3]>,
resolved: AddrList,
tries: u16,
timeout: u16,
next: Time,
final_timeout: Option<Time>
final_timeout: Option<Time>,
}
pub struct GenericCloud<D: Device, P: Protocol, S: Socket, TS: TimeSource> {
node_id: NodeId,
config: Config,
@ -72,7 +74,7 @@ pub struct GenericCloud<D: Device, P: Protocol, S: Socket, TS: TimeSource> {
broadcast: bool,
peers: HashMap<SocketAddr, PeerData, Hash>,
reconnect_peers: SmallVec<[ReconnectEntry; 3]>,
own_addresses: SmallVec<[SocketAddr; 3]>,
own_addresses: AddrList,
pending_inits: HashMap<SocketAddr, PeerCrypto<NodeInfo>, Hash>,
table: ClaimTable<TS>,
socket: S,
@ -92,26 +94,22 @@ pub struct GenericCloud<D: Device, P: Protocol, S: Socket, TS: TimeSource> {
traffic: TrafficStats,
beacon_serializer: BeaconSerializer<TS>,
_dummy_p: PhantomData<P>,
_dummy_ts: PhantomData<TS>
_dummy_ts: PhantomData<TS>,
}
impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS> {
#[allow(clippy::too_many_arguments)]
pub fn new(config: &Config, device: D, port_forwarding: Option<PortForwarding>, stats_file: Option<File>) -> Self {
let socket = match S::listen(config.listen) {
Ok(socket) => socket,
Err(err) => fail!("Failed to open socket {}: {}", config.listen, err)
};
pub fn new(
config: &Config, socket: S, device: D, port_forwarding: Option<PortForwarding>, stats_file: Option<File>,
) -> Self {
let (learning, broadcast) = match config.mode {
Mode::Normal => {
match config.device_type {
Type::Tap => (true, true),
Type::Tun | Type::Dummy => (false, false)
}
}
Mode::Normal => match config.device_type {
Type::Tap => (true, true),
Type::Tun => (false, false),
},
Mode::Router => (false, false),
Mode::Switch => (true, true),
Mode::Hub => (false, true)
Mode::Hub => (false, true),
};
let mut claims = SmallVec::with_capacity(config.claims.len());
for s in &config.claims {
@ -124,7 +122,10 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
info!("Auto-claiming {} due to interface address", range);
claims.push(range);
}
Err(e) => error!("{}", e)
Err(Error::DeviceIo(_, e)) if e.kind() == io::ErrorKind::AddrNotAvailable => {
info!("No address set on interface.")
}
Err(e) => error!("{}", e),
}
}
let now = TS::now();
@ -159,7 +160,7 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
crypto,
config: config.clone(),
_dummy_p: PhantomData,
_dummy_ts: PhantomData
_dummy_ts: PhantomData,
};
res.initialize();
res
@ -189,7 +190,7 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
match self.socket.send(msg_data.message(), *addr) {
Ok(written) if written == msg_data.len() => Ok(()),
Ok(_) => Err(Error::Socket("Sent out truncated packet")),
Err(e) => Err(Error::SocketIo("IOError when sending", e))
Err(e) => Err(Error::SocketIo("IOError when sending", e)),
}?
}
Ok(())
@ -197,21 +198,23 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
#[inline]
fn send_to(&mut self, addr: SocketAddr, msg: &mut MsgBuffer) -> Result<(), Error> {
// HOT PATH
debug!("Sending msg with {} bytes to {}", msg.len(), addr);
self.traffic.count_out_traffic(addr, msg.len());
match self.socket.send(msg.message(), addr) {
Ok(written) if written == msg.len() => Ok(()),
Ok(_) => Err(Error::Socket("Sent out truncated packet")),
Err(e) => Err(Error::SocketIo("IOError when sending", e))
Err(e) => Err(Error::SocketIo("IOError when sending", e)),
}
}
#[inline]
fn send_msg(&mut self, addr: SocketAddr, type_: u8, msg: &mut MsgBuffer) -> Result<(), Error> {
// HOT PATH
debug!("Sending msg with {} bytes to {}", msg.len(), addr);
let peer = match self.peers.get_mut(&addr) {
Some(peer) => peer,
None => return Err(Error::Message("Sending to node that is not a peer"))
None => return Err(Error::Message("Sending to node that is not a peer")),
};
peer.crypto.send_message(type_, msg)?;
self.send_to(addr, msg)
@ -219,11 +222,20 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
pub fn reset_own_addresses(&mut self) -> io::Result<()> {
self.own_addresses.clear();
self.own_addresses.push(self.socket.address().map(mapped_addr)?);
let socket_addr = self.socket.address().map(mapped_addr)?;
// 1) Specified advertise addresses
for addr in &self.config.advertise_addresses {
self.own_addresses.push(parse_listen(addr, socket_addr.port()));
}
// 2) Address of UDP socket
self.own_addresses.push(socket_addr);
// 3) Addresses from port forwarding
if let Some(ref pfw) = self.port_forwarding {
self.own_addresses.push(pfw.get_internal_ip().into());
self.own_addresses.push(pfw.get_external_ip().into());
}
debug!("Own addresses: {:?}", self.own_addresses);
// TODO: detect address changes and call event
Ok(())
}
@ -237,12 +249,8 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
///
/// This method adds a peer to the list of nodes to reconnect to. A periodic task will try to
/// connect to the peer if it is not already connected.
pub fn add_reconnect_peer(&mut self, mut add: String) {
pub fn add_reconnect_peer(&mut self, add: String) {
let now = TS::now();
if add.find(':').unwrap_or(0) <= add.find(']').unwrap_or(0) {
// : not present or only in IPv6 address
add = format!("{}:{}", add, DEFAULT_PORT)
}
let resolved = match resolve(&add as &str) {
Ok(addrs) => addrs,
Err(err) => {
@ -256,7 +264,7 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
timeout: 1,
resolved,
next: now,
final_timeout: None
final_timeout: None,
})
}
@ -275,9 +283,16 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
|| self.peers.contains_key(addr)
|| self.pending_inits.contains_key(addr)
{
return Ok(())
return Ok(());
}
}
if !addrs.is_empty() {
self.config.call_hook(
"peer_connecting",
vec![("PEER", format!("{:?}", addr_nice(addrs[0]))), ("IFNAME", self.device.ifname().to_owned())],
true,
);
}
// Send a message to each resolved address
for a in addrs {
// Ignore error this time
@ -288,8 +303,8 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
fn create_node_info(&self) -> NodeInfo {
let mut peers = smallvec![];
for (addr, peer) in &self.peers {
peers.push(PeerInfo { node_id: Some(peer.node_id), addrs: smallvec![*addr] })
for peer in self.peers.values() {
peers.push(PeerInfo { node_id: Some(peer.node_id), addrs: peer.addrs.clone() })
}
if peers.len() > 20 {
let mut rng = rand::thread_rng();
@ -300,7 +315,8 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
node_id: self.node_id,
peers,
claims: self.claims.clone(),
peer_timeout: Some(self.peer_timeout_publish)
peer_timeout: Some(self.peer_timeout_publish),
addrs: self.own_addresses.clone(),
}
}
@ -310,7 +326,7 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
|| self.own_addresses.contains(&addr)
|| self.pending_inits.contains_key(&addr)
{
return Ok(())
return Ok(());
}
debug!("Connecting to {:?}", addr);
let payload = self.create_node_info();
@ -330,7 +346,7 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
Err(_) => del.push(addr),
Ok(MessageResult::None) => (),
Ok(MessageResult::Reply) => self.send_to(addr, &mut msg)?,
Ok(_) => unreachable!()
Ok(_) => unreachable!(),
}
}
for addr in self.peers.keys().copied().collect::<SmallVec<[SocketAddr; 16]>>() {
@ -339,7 +355,7 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
Err(_) => del.push(addr),
Ok(MessageResult::None) => (),
Ok(MessageResult::Reply) => self.send_to(addr, &mut msg)?,
Ok(_) => unreachable!()
Ok(_) => unreachable!(),
}
}
for addr in del {
@ -356,18 +372,18 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
// Connect to those reconnect_peers that are due
for entry in self.reconnect_peers.clone() {
if entry.next > now {
continue
continue;
}
self.connect(&entry.resolved as &[SocketAddr])?;
}
for entry in &mut self.reconnect_peers {
// Schedule for next second if node is connected
for addr in &entry.resolved {
if self.peers.contains_key(&addr) {
if self.peers.contains_key(addr) {
entry.tries = 0;
entry.timeout = 1;
entry.next = now + 1;
continue
continue;
}
}
// Resolve entries anew
@ -375,19 +391,17 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
if *next_resolve <= now {
match resolve(address as &str) {
Ok(addrs) => entry.resolved = addrs,
Err(_) => {
match resolve(&format!("{}:{}", address, DEFAULT_PORT)) {
Ok(addrs) => entry.resolved = addrs,
Err(err) => warn!("Failed to resolve {}: {}", address, err)
}
}
Err(_) => match resolve(&format!("{}:{}", address, DEFAULT_PORT)) {
Ok(addrs) => entry.resolved = addrs,
Err(err) => warn!("Failed to resolve {}: {}", address, err),
},
}
*next_resolve = now + RESOLVE_INTERVAL;
}
}
// Ignore if next attempt is already in the future
if entry.next > now {
continue
continue;
}
// Exponential back-off: every 10 tries, the interval doubles
entry.tries += 1;
@ -410,7 +424,7 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
let now = TS::now();
let mut buffer = MsgBuffer::new(SPACE_BEFORE);
let mut del: SmallVec<[SocketAddr; 3]> = SmallVec::new();
for (&addr, ref data) in &self.peers {
for (&addr, data) in &self.peers {
if data.timeout < now {
del.push(addr);
}
@ -428,11 +442,6 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
pfw.check_extend();
}
let now = TS::now();
// Periodically reset own peers
if self.next_own_address_reset <= now {
self.reset_own_addresses().map_err(|err| Error::SocketIo("Failed to get own addresses", err))?;
self.next_own_address_reset = now + OWN_ADDRESS_RESET_INTERVAL;
}
// Periodically send peer list to peers
if self.next_peers <= now {
debug!("Send peer list to all peers");
@ -441,7 +450,7 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
self.broadcast_msg(MESSAGE_TYPE_NODE_INFO, &mut buffer)?;
// Reschedule for next update
let min_peer_timeout = self.peers.iter().map(|p| p.1.peer_timeout).min().unwrap_or(DEFAULT_PEER_TIMEOUT);
let interval = min(self.update_freq as u16, max(min_peer_timeout / 2 - 60, 1));
let interval = min(self.update_freq, max(min_peer_timeout / 2 - 60, 1));
self.next_peers = now + Time::from(interval);
}
self.reconnect_to_peers()?;
@ -463,6 +472,11 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
self.load_beacon()?;
self.next_beacon = now + Time::from(self.config.beacon_interval);
}
// Periodically reset own peers
if self.next_own_address_reset <= now {
self.reset_own_addresses().map_err(|err| Error::SocketIo("Failed to get own addresses", err))?;
self.next_own_address_reset = now + OWN_ADDRESS_RESET_INTERVAL;
}
Ok(())
}
@ -477,7 +491,7 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
.map_err(|e| Error::BeaconIo("Failed to call beacon command", e))?;
} else {
self.beacon_serializer
.write_to_file(&peers, &path)
.write_to_file(&peers, path)
.map_err(|e| Error::BeaconIo("Failed to write beacon to file", e))?;
}
}
@ -492,15 +506,15 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
self.beacon_serializer
.read_from_cmd(path, Some(50))
.map_err(|e| Error::BeaconIo("Failed to call beacon command", e))?;
return Ok(())
return Ok(());
} else {
peers = self
.beacon_serializer
.read_from_file(&path, Some(50))
.read_from_file(path, Some(50))
.map_err(|e| Error::BeaconIo("Failed to read beacon from file", e))?;
}
} else {
return Ok(())
return Ok(());
}
debug!("Loaded beacon with peers: {:?}", peers);
for peer in peers {
@ -585,7 +599,7 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
match self.socket.send(msg_data, *addr) {
Ok(written) if written == msg_data.len() => Ok(()),
Ok(_) => Err(Error::Socket("Sent out truncated packet")),
Err(e) => Err(Error::SocketIo("IOError when sending", e))
Err(e) => Err(Error::SocketIo("IOError when sending", e)),
}?
} else {
error!("Failed to resolve statsd server {}", endpoint);
@ -595,15 +609,18 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
}
pub fn handle_interface_data(&mut self, data: &mut MsgBuffer) -> Result<(), Error> {
// HOT PATH
let (src, dst) = P::parse(data.message())?;
debug!("Read data from interface: src: {}, dst: {}, {} bytes", src, dst, data.len());
self.traffic.count_out_payload(dst, src, data.len());
match self.table.lookup(dst) {
Some(addr) => {
// HOT PATH
// Peer found for destination
debug!("Found destination for {} => {}", dst, addr);
self.send_msg(addr, MESSAGE_TYPE_DATA, data)?;
if !self.peers.contains_key(&addr) {
// COLD PATH
// If the peer is not actually connected, remove the entry in the table and try
// to reconnect.
warn!("Destination for {} not found in peers: {}", dst, addr_nice(addr));
@ -612,6 +629,7 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
}
}
None => {
// COLD PATH
if self.broadcast {
debug!("No destination for {} found, broadcasting", dst);
self.broadcast_msg(MESSAGE_TYPE_DATA, data)?;
@ -626,14 +644,28 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
fn add_new_peer(&mut self, addr: SocketAddr, info: NodeInfo) -> Result<(), Error> {
info!("Added peer {}", addr_nice(addr));
self.config.call_hook(
"peer_connected",
vec![
("PEER", format!("{:?}", addr_nice(addr))),
("IFNAME", self.device.ifname().to_owned()),
("CLAIMS", info.claims.iter().map(|r| format!("{:?}", r)).collect::<Vec<String>>().join(" ")),
("NODE_ID", bytes_to_hex(&info.node_id)),
],
true,
);
if let Some(init) = self.pending_inits.remove(&addr) {
self.peers.insert(addr, PeerData {
crypto: init,
node_id: info.node_id,
peer_timeout: info.peer_timeout.unwrap_or(DEFAULT_PEER_TIMEOUT),
last_seen: TS::now(),
timeout: TS::now() + self.config.peer_timeout as Time
});
self.peers.insert(
addr,
PeerData {
addrs: info.addrs.clone(),
crypto: init,
node_id: info.node_id,
peer_timeout: info.peer_timeout.unwrap_or(DEFAULT_PEER_TIMEOUT),
last_seen: TS::now(),
timeout: TS::now() + self.config.peer_timeout as Time,
},
);
self.update_peer_info(addr, Some(info))?;
} else {
error!("No init for new peer {}", addr_nice(addr));
@ -642,9 +674,18 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
}
fn remove_peer(&mut self, addr: SocketAddr) {
if let Some(_peer) = self.peers.remove(&addr) {
if let Some(peer) = self.peers.remove(&addr) {
info!("Closing connection to {}", addr_nice(addr));
self.table.remove_claims(addr);
self.config.call_hook(
"peer_disconnected",
vec![
("PEER", format!("{:?}", addr)),
("IFNAME", self.device.ifname().to_owned()),
("NODE_ID", bytes_to_hex(&peer.node_id)),
],
true,
);
}
}
@ -652,16 +693,22 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
'outer: for peer in peers {
for addr in &peer.addrs {
if self.peers.contains_key(addr) {
continue 'outer
continue 'outer;
}
}
if let Some(node_id) = peer.node_id {
if self.node_id == node_id {
continue 'outer
// Check addresses and add addresses that we don't know to own addresses
for addr in &peer.addrs {
if !self.own_addresses.contains(addr) {
self.own_addresses.push(*addr)
}
}
continue 'outer;
}
for p in self.peers.values() {
if p.node_id == node_id {
continue 'outer
continue 'outer;
}
}
}
@ -673,10 +720,20 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
fn update_peer_info(&mut self, addr: SocketAddr, info: Option<NodeInfo>) -> Result<(), Error> {
if let Some(peer) = self.peers.get_mut(&addr) {
peer.last_seen = TS::now();
peer.timeout = TS::now() + self.config.peer_timeout as Time
peer.timeout = TS::now() + self.config.peer_timeout as Time;
if let Some(info) = &info {
// Update peer addresses, always add seen address
peer.addrs.clear();
peer.addrs.push(addr);
for addr in &info.addrs {
if !peer.addrs.contains(addr) {
peer.addrs.push(*addr);
}
}
}
} else {
error!("Received peer update from non peer {}", addr_nice(addr));
return Ok(())
return Ok(());
}
if let Some(info) = info {
debug!("Adding claims of peer {}: {:?}", addr_nice(addr), info.claims);
@ -688,13 +745,14 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
}
fn handle_payload_from(&mut self, peer: SocketAddr, data: &mut MsgBuffer) -> Result<(), Error> {
// HOT PATH
let (src, dst) = P::parse(data.message())?;
let len = data.len();
debug!("Writing data to device: {} bytes", len);
self.traffic.count_in_payload(src, dst, len);
if let Err(e) = self.device.write(data) {
error!("Failed to send via device: {}", e);
return Err(e)
return Err(e);
}
if self.learning {
// Learn single address
@ -704,47 +762,72 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
}
fn handle_message(
&mut self, src: SocketAddr, msg_result: MessageResult<NodeInfo>, data: &mut MsgBuffer
&mut self, src: SocketAddr, msg_result: MessageResult<NodeInfo>, data: &mut MsgBuffer,
) -> Result<(), Error> {
// HOT PATH
match msg_result {
MessageResult::Message(type_) => {
// HOT PATH
match type_ {
MESSAGE_TYPE_DATA => self.handle_payload_from(src, data)?,
MESSAGE_TYPE_DATA => {
// HOT PATH
self.handle_payload_from(src, data)?
}
MESSAGE_TYPE_NODE_INFO => {
// COLD PATH
let info = match NodeInfo::decode(Cursor::new(data.message())) {
Ok(val) => val,
Err(err) => {
self.traffic.count_invalid_protocol(data.len());
return Err(err)
return Err(err);
}
};
self.update_peer_info(src, Some(info))?
}
MESSAGE_TYPE_KEEPALIVE => self.update_peer_info(src, None)?,
MESSAGE_TYPE_CLOSE => self.remove_peer(src),
MESSAGE_TYPE_KEEPALIVE => {
// COLD PATH
self.update_peer_info(src, None)?
}
MESSAGE_TYPE_CLOSE => {
// COLD PATH
self.remove_peer(src)
}
_ => {
// COLD PATH
self.traffic.count_invalid_protocol(data.len());
return Err(Error::Message("Unknown message type"))
return Err(Error::Message("Unknown message type"));
}
}
}
MessageResult::Initialized(info) => self.add_new_peer(src, info)?,
MessageResult::Initialized(info) => {
// COLD PATH
self.add_new_peer(src, info)?
}
MessageResult::InitializedWithReply(info) => {
// COLD PATH
self.add_new_peer(src, info)?;
self.send_to(src, data)?
}
MessageResult::Reply => self.send_to(src, data)?,
MessageResult::None => ()
MessageResult::Reply => {
// COLD PATH
self.send_to(src, data)?
}
MessageResult::None => {
// COLD PATH
}
}
Ok(())
}
pub fn handle_net_message(&mut self, src: SocketAddr, data: &mut MsgBuffer) -> Result<(), Error> {
// HOT PATH
let src = mapped_addr(src);
debug!("Received {} bytes from {}", data.len(), src);
let msg_result = if let Some(init) = self.pending_inits.get_mut(&src) {
// COLD PATH
init.handle_message(data)
} else if is_init_message(data.message()) {
// COLD PATH
let mut result = None;
if let Some(peer) = self.peers.get_mut(&src) {
if peer.crypto.has_init() {
@ -758,25 +841,40 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
let msg_result = init.handle_message(data);
match msg_result {
Ok(res) => {
self.config.call_hook(
"peer_connecting",
vec![
("PEER", format!("{:?}", addr_nice(src))),
("IFNAME", self.device.ifname().to_owned()),
],
true,
);
self.pending_inits.insert(src, init);
Ok(res)
}
Err(err) => {
self.traffic.count_invalid_protocol(data.len());
return Err(err)
return Err(err);
}
}
}
} else if let Some(peer) = self.peers.get_mut(&src) {
// HOT PATH
peer.crypto.handle_message(data)
} else {
// COLD PATH
info!("Ignoring non-init message from unknown peer {}", addr_nice(src));
self.traffic.count_invalid_protocol(data.len());
return Ok(())
return Ok(());
};
// HOT PATH
match msg_result {
Ok(val) => self.handle_message(src, val, data),
Ok(val) => {
// HOT PATH
self.handle_message(src, val, data)
}
Err(err) => {
// COLD PATH
self.traffic.count_invalid_protocol(data.len());
Err(err)
}
@ -790,26 +888,36 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
}
fn handle_socket_event(&mut self, buffer: &mut MsgBuffer) {
// HOT PATH
let src = try_fail!(self.socket.receive(buffer), "Failed to read from network socket: {}");
self.traffic.count_in_traffic(src, buffer.len());
match self.handle_net_message(src, buffer) {
Err(e @ Error::CryptoInitFatal(_)) => {
// COLD PATH
debug!("Fatal crypto init error from {}: {}", src, e);
info!("Closing pending connection to {} due to error in crypto init", addr_nice(src));
self.pending_inits.remove(&src);
self.config.call_hook(
"peer_disconnected",
vec![("PEER", format!("{:?}", addr_nice(src))), ("IFNAME", self.device.ifname().to_owned())],
true,
);
}
Err(e @ Error::CryptoInit(_)) => {
// COLD PATH
debug!("Recoverable init error from {}: {}", src, e);
info!("Ignoring invalid init message from peer {}", addr_nice(src));
}
Err(e) => {
// COLD PATH
error!("{}", e);
}
Ok(_) => {}
Ok(_) => {} // HOT PATH
}
}
fn handle_device_event(&mut self, buffer: &mut MsgBuffer) {
// HOT PATH
try_fail!(self.device.read(buffer), "Failed to read from device: {}");
if let Err(e) = self.handle_interface_data(buffer) {
error!("{}", e);
@ -825,12 +933,18 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
/// Also, this method will call `housekeep` every second.
pub fn run(&mut self) {
let ctrlc = CtrlC::new();
let waiter = try_fail!(WaitImpl::new(&self.socket, &self.device, 1000), "Failed to setup poll: {}");
let waiter = try_fail!(
WaitImpl::new(self.socket.as_raw_fd(), self.device.as_raw_fd(), 1000),
"Failed to setup poll: {}"
);
let mut buffer = MsgBuffer::new(SPACE_BEFORE);
let mut poll_error = false;
self.config.call_hook("vpn_started", vec![("IFNAME", self.device.ifname())], true);
for evt in waiter {
// HOT PATH
match evt {
WaitResult::Error(err) => {
// COLD PATH
if poll_error {
fail!("Poll wait failed again: {}", err);
}
@ -839,12 +953,13 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
}
WaitResult::Timeout => {}
WaitResult::Socket => self.handle_socket_event(&mut buffer),
WaitResult::Device => self.handle_device_event(&mut buffer)
WaitResult::Device => self.handle_device_event(&mut buffer),
}
if self.next_housekeep < TS::now() {
// COLD PATH
poll_error = false;
if ctrlc.was_pressed() {
break
break;
}
if let Err(e) = self.housekeep() {
error!("{}", e)
@ -853,6 +968,7 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
}
}
info!("Shutting down...");
self.config.call_hook("vpn_shutdown", vec![("IFNAME", self.device.ifname())], true);
buffer.clear();
self.broadcast_msg(MESSAGE_TYPE_CLOSE, &mut buffer).ok();
if let Some(ref path) = self.config.beacon_store {
@ -867,10 +983,12 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
}
}
#[cfg(test)] use super::device::MockDevice;
#[cfg(test)] use super::net::MockSocket;
#[cfg(test)] use super::util::MockTimeSource;
#[cfg(test)]
use super::device::MockDevice;
#[cfg(test)]
use super::net::MockSocket;
#[cfg(test)]
use super::util::MockTimeSource;
#[cfg(test)]
impl<P: Protocol> GenericCloud<MockDevice, P, MockSocket, MockTimeSource> {

View File

@ -1,33 +1,16 @@
// 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};
use super::{device::Type, types::Mode, util::run_cmd, util::Duration};
pub use crate::crypto::Config as CryptoConfig;
use std::{
cmp::max,
net::{IpAddr, Ipv6Addr, SocketAddr}
};
use structopt::StructOpt;
use std::{cmp::max, collections::HashMap, ffi::OsStr, process, thread};
use structopt::{clap::Shell, StructOpt};
pub const DEFAULT_PEER_TIMEOUT: u16 = 300;
pub const DEFAULT_PORT: u16 = 3210;
fn parse_listen(addr: &str) -> SocketAddr {
if let Some(addr) = addr.strip_prefix("*:") {
let port = try_fail!(addr.parse::<u16>(), "Invalid port: {}");
SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), port)
} else if addr.contains(':') {
try_fail!(addr.parse::<SocketAddr>(), "Invalid address: {}: {}", addr)
} else {
let port = try_fail!(addr.parse::<u16>(), "Invalid port: {}");
SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), port)
}
}
#[derive(Deserialize, Debug, PartialEq, Clone)]
pub struct Config {
pub device_type: Type,
@ -36,12 +19,13 @@ pub struct Config {
pub fix_rp_filter: bool,
pub ip: Option<String>,
pub advertise_addresses: Vec<String>,
pub ifup: Option<String>,
pub ifdown: Option<String>,
pub crypto: CryptoConfig,
pub listen: SocketAddr,
pub listen: String,
pub peers: Vec<String>,
pub peer_timeout: Duration,
pub keepalive: Option<Duration>,
@ -60,7 +44,9 @@ pub struct Config {
pub statsd_server: Option<String>,
pub statsd_prefix: Option<String>,
pub user: Option<String>,
pub group: Option<String>
pub group: Option<String>,
pub hook: Option<String>,
pub hooks: HashMap<String, String>,
}
impl Default for Config {
@ -71,10 +57,11 @@ impl Default for Config {
device_path: None,
fix_rp_filter: false,
ip: None,
advertise_addresses: vec![],
ifup: None,
ifdown: None,
crypto: CryptoConfig::default(),
listen: "[::]:3210".parse::<SocketAddr>().unwrap(),
listen: "3210".to_string(),
peers: vec![],
peer_timeout: DEFAULT_PEER_TIMEOUT as Duration,
keepalive: None,
@ -93,7 +80,9 @@ impl Default for Config {
statsd_server: None,
statsd_prefix: None,
user: None,
group: None
group: None,
hook: None,
hooks: HashMap::new(),
}
}
}
@ -118,6 +107,9 @@ impl Config {
if let Some(val) = file.ip {
self.ip = Some(val);
}
if let Some(mut val) = file.advertise_addresses {
self.advertise_addresses.append(&mut val);
}
if let Some(val) = file.ifup {
self.ifup = Some(val);
}
@ -125,7 +117,7 @@ impl Config {
self.ifdown = Some(val);
}
if let Some(val) = file.listen {
self.listen = parse_listen(&val);
self.listen = val;
}
if let Some(mut val) = file.peers {
self.peers.append(&mut val);
@ -198,6 +190,12 @@ impl Config {
if !file.crypto.algorithms.is_empty() {
self.crypto.algorithms = file.crypto.algorithms.clone();
}
if let Some(val) = file.hook {
self.hook = Some(val)
}
for (k, v) in file.hooks {
self.hooks.insert(k, v);
}
}
pub fn merge_args(&mut self, mut args: Args) {
@ -219,11 +217,12 @@ impl Config {
if let Some(val) = args.ifup {
self.ifup = Some(val);
}
self.advertise_addresses.append(&mut args.advertise_addresses);
if let Some(val) = args.ifdown {
self.ifdown = Some(val);
}
if let Some(val) = args.listen {
self.listen = parse_listen(&val);
self.listen = val;
}
self.peers.append(&mut args.peers);
if let Some(val) = args.peer_timeout {
@ -291,17 +290,88 @@ impl Config {
if !args.algorithms.is_empty() {
self.crypto.algorithms = args.algorithms.clone();
}
for s in args.hook {
if s.contains(':') {
let pos = s.find(':').unwrap();
let name = &s[..pos];
let hook = &s[pos + 1..];
self.hooks.insert(name.to_string(), hook.to_string());
} else {
self.hook = Some(s);
}
}
}
pub fn into_config_file(self) -> ConfigFile {
ConfigFile {
auto_claim: Some(self.auto_claim),
claims: Some(self.claims),
beacon: Some(ConfigFileBeacon {
store: self.beacon_store,
load: self.beacon_load,
interval: Some(self.beacon_interval),
password: self.beacon_password,
}),
device: Some(ConfigFileDevice {
name: Some(self.device_name),
path: self.device_path,
type_: Some(self.device_type),
fix_rp_filter: Some(self.fix_rp_filter),
}),
crypto: self.crypto,
group: self.group,
user: self.user,
ifup: self.ifup,
ifdown: self.ifdown,
ip: self.ip,
advertise_addresses: Some(self.advertise_addresses),
keepalive: self.keepalive,
listen: Some(self.listen),
mode: Some(self.mode),
peer_timeout: Some(self.peer_timeout),
peers: Some(self.peers),
pid_file: self.pid_file,
port_forwarding: Some(self.port_forwarding),
stats_file: self.stats_file,
statsd: Some(ConfigFileStatsd { server: self.statsd_server, prefix: self.statsd_prefix }),
switch_timeout: Some(self.switch_timeout),
hook: self.hook,
hooks: self.hooks,
}
}
pub fn get_keepalive(&self) -> Duration {
match self.keepalive {
Some(dur) => dur,
None => max(self.peer_timeout / 2 - 60, 1)
None => max(self.peer_timeout / 2 - 60, 1),
}
}
pub fn call_hook(
&self, event: &'static str, envs: impl IntoIterator<Item = (&'static str, impl AsRef<OsStr>)>, detach: bool,
) {
let mut script = None;
if let Some(ref s) = self.hook {
script = Some(s);
}
if let Some(s) = self.hooks.get(event) {
script = Some(s);
}
if script.is_none() {
return;
}
let script = script.unwrap();
let mut cmd = process::Command::new("sh");
cmd.arg("-c").arg(script).envs(envs).env("EVENT", event);
debug!("Running event script: {:?}", cmd);
if detach {
thread::spawn(move || run_cmd(cmd));
} else {
run_cmd(cmd)
}
}
}
#[derive(StructOpt, Debug, Default)]
pub struct Args {
/// Read configuration options from the specified file.
@ -325,7 +395,7 @@ pub struct Args {
pub mode: Option<Mode>,
/// The shared password to encrypt all traffic
#[structopt(short, long, required_unless_one = &["private-key", "config", "genkey", "version"], env)]
#[structopt(short, long, env)]
pub password: Option<String>,
/// The private key to use
@ -404,6 +474,10 @@ pub struct Args {
#[structopt(long)]
pub ip: Option<String>,
/// A list of IP Addresses to advertise as our external address(s)
#[structopt(long = "advertise_addresses", use_delimiter = true)]
pub advertise_addresses: Vec<String>,
/// A command to setup the network interface
#[structopt(long)]
pub ifup: Option<String>,
@ -416,10 +490,6 @@ pub struct Args {
#[structopt(long)]
pub version: bool,
/// Generate and print a key-pair and exit
#[structopt(long, conflicts_with = "private_key")]
pub genkey: bool,
/// Disable automatic port forwarding
#[structopt(long)]
pub no_port_forwarding: bool,
@ -456,9 +526,63 @@ pub struct Args {
#[structopt(long)]
pub log_file: Option<String>,
/// Call script on event
#[structopt(long)]
pub hook: Vec<String>,
#[structopt(subcommand)]
pub cmd: Option<Command>,
}
#[derive(StructOpt, Debug)]
pub enum Command {
/// Generate and print a key-pair and exit
#[structopt(name = "genkey", alias = "gen-key")]
GenKey {
/// The shared password to encrypt all traffic
#[structopt(short, long, env)]
password: Option<String>,
},
/// Run a websocket proxy
#[cfg(feature = "websocket")]
#[structopt(alias = "wsproxy")]
WsProxy {
/// Websocket listen address IP:PORT
#[structopt(long, short, default_value = "3210")]
listen: String,
},
/// Migrate an old config file
#[structopt(long, alias = "migrate", requires = "config")]
pub migrate_config: bool
#[structopt(alias = "migrate")]
MigrateConfig {
/// Config file
#[structopt(long)]
config_file: String,
},
/// Generate shell completions
Completion {
/// Shell to create completions for
#[structopt(long, default_value = "bash")]
shell: Shell,
},
/// Edit the config of a network
#[cfg(feature = "wizard")]
Config {
/// Name of the network
#[structopt(short, long)]
name: Option<String>,
},
/// Install required utility files
#[cfg(feature = "installer")]
Install {
/// Remove installed files again
#[structopt(long)]
uninstall: bool,
},
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Default)]
@ -468,7 +592,7 @@ pub struct ConfigFileDevice {
pub type_: Option<Type>,
pub name: Option<String>,
pub path: Option<String>,
pub fix_rp_filter: Option<bool>
pub fix_rp_filter: Option<bool>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Default)]
@ -477,14 +601,14 @@ pub struct ConfigFileBeacon {
pub store: Option<String>,
pub load: Option<String>,
pub interval: Option<Duration>,
pub password: Option<String>
pub password: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Default)]
#[serde(rename_all = "kebab-case", deny_unknown_fields, default)]
pub struct ConfigFileStatsd {
pub server: Option<String>,
pub prefix: Option<String>
pub prefix: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Default)]
@ -493,6 +617,7 @@ pub struct ConfigFile {
pub device: Option<ConfigFileDevice>,
pub ip: Option<String>,
pub advertise_addresses: Option<Vec<String>>,
pub ifup: Option<String>,
pub ifdown: Option<String>,
@ -512,10 +637,11 @@ pub struct ConfigFile {
pub stats_file: Option<String>,
pub statsd: Option<ConfigFileStatsd>,
pub user: Option<String>,
pub group: Option<String>
pub group: Option<String>,
pub hook: Option<String>,
pub hooks: HashMap<String, String>,
}
#[test]
fn config_file() {
let config_file = "
@ -524,6 +650,9 @@ device:
name: vpncloud%d
path: /dev/net/tun
ip: 10.0.1.1/16
advertise-addresses:
- 192.168.0.1
- 192.168.1.1
ifup: ifconfig $IFNAME 10.0.1.1/16 mtu 1400 up
ifdown: 'true'
peers:
@ -549,78 +678,52 @@ statsd:
server: example.com:1234
prefix: prefix
";
assert_eq!(serde_yaml::from_str::<ConfigFile>(config_file).unwrap(), ConfigFile {
device: Some(ConfigFileDevice {
type_: Some(Type::Tun),
name: Some("vpncloud%d".to_string()),
path: Some("/dev/net/tun".to_string()),
fix_rp_filter: None
}),
ip: Some("10.0.1.1/16".to_string()),
ifup: Some("ifconfig $IFNAME 10.0.1.1/16 mtu 1400 up".to_string()),
ifdown: Some("true".to_string()),
crypto: CryptoConfig::default(),
listen: None,
peers: Some(vec!["remote.machine.foo:3210".to_string(), "remote.machine.bar:3210".to_string()]),
peer_timeout: Some(600),
keepalive: Some(840),
beacon: Some(ConfigFileBeacon {
store: Some("/run/vpncloud.beacon.out".to_string()),
load: Some("/run/vpncloud.beacon.in".to_string()),
interval: Some(3600),
password: Some("test123".to_string())
}),
mode: Some(Mode::Normal),
switch_timeout: Some(300),
claims: Some(vec!["10.0.1.0/24".to_string()]),
auto_claim: None,
port_forwarding: Some(true),
user: Some("nobody".to_string()),
group: Some("nogroup".to_string()),
pid_file: Some("/run/vpncloud.run".to_string()),
stats_file: Some("/var/log/vpncloud.stats".to_string()),
statsd: Some(ConfigFileStatsd {
server: Some("example.com:1234".to_string()),
prefix: Some("prefix".to_string())
})
})
assert_eq!(
serde_yaml::from_str::<ConfigFile>(config_file).unwrap(),
ConfigFile {
device: Some(ConfigFileDevice {
type_: Some(Type::Tun),
name: Some("vpncloud%d".to_string()),
path: Some("/dev/net/tun".to_string()),
fix_rp_filter: None
}),
ip: Some("10.0.1.1/16".to_string()),
advertise_addresses: Some(vec!["192.168.0.1".to_string(), "192.168.1.1".to_string()]),
ifup: Some("ifconfig $IFNAME 10.0.1.1/16 mtu 1400 up".to_string()),
ifdown: Some("true".to_string()),
crypto: CryptoConfig::default(),
listen: None,
peers: Some(vec!["remote.machine.foo:3210".to_string(), "remote.machine.bar:3210".to_string()]),
peer_timeout: Some(600),
keepalive: Some(840),
beacon: Some(ConfigFileBeacon {
store: Some("/run/vpncloud.beacon.out".to_string()),
load: Some("/run/vpncloud.beacon.in".to_string()),
interval: Some(3600),
password: Some("test123".to_string())
}),
mode: Some(Mode::Normal),
switch_timeout: Some(300),
claims: Some(vec!["10.0.1.0/24".to_string()]),
auto_claim: None,
port_forwarding: Some(true),
user: Some("nobody".to_string()),
group: Some("nogroup".to_string()),
pid_file: Some("/run/vpncloud.run".to_string()),
stats_file: Some("/var/log/vpncloud.stats".to_string()),
statsd: Some(ConfigFileStatsd {
server: Some("example.com:1234".to_string()),
prefix: Some("prefix".to_string())
}),
hook: None,
hooks: HashMap::new()
}
)
}
#[test]
fn default_config_as_default() {
let mut default_config = Config {
device_type: Type::Dummy,
device_name: "".to_string(),
device_path: None,
fix_rp_filter: false,
ip: None,
ifup: None,
ifdown: None,
crypto: CryptoConfig::default(),
listen: "[::]:3210".parse::<SocketAddr>().unwrap(),
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
};
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]
@ -631,9 +734,10 @@ fn config_merge() {
type_: Some(Type::Tun),
name: Some("vpncloud%d".to_string()),
path: None,
fix_rp_filter: None
fix_rp_filter: None,
}),
ip: None,
advertise_addresses: Some(vec![]),
ifup: Some("ifconfig $IFNAME 10.0.1.1/16 mtu 1400 up".to_string()),
ifdown: Some("true".to_string()),
crypto: CryptoConfig::default(),
@ -645,7 +749,7 @@ fn config_merge() {
store: Some("/run/vpncloud.beacon.out".to_string()),
load: Some("/run/vpncloud.beacon.in".to_string()),
interval: Some(7200),
password: Some("test123".to_string())
password: Some("test123".to_string()),
}),
mode: Some(Mode::Normal),
switch_timeout: Some(300),
@ -658,36 +762,42 @@ fn config_merge() {
stats_file: Some("/var/log/vpncloud.stats".to_string()),
statsd: Some(ConfigFileStatsd {
server: Some("example.com:1234".to_string()),
prefix: Some("prefix".to_string())
})
});
assert_eq!(config, Config {
device_type: Type::Tun,
device_name: "vpncloud%d".to_string(),
device_path: None,
ip: None,
ifup: Some("ifconfig $IFNAME 10.0.1.1/16 mtu 1400 up".to_string()),
ifdown: Some("true".to_string()),
listen: "[::]:3210".parse::<SocketAddr>().unwrap(),
peers: vec!["remote.machine.foo:3210".to_string(), "remote.machine.bar:3210".to_string()],
peer_timeout: 600,
keepalive: Some(840),
switch_timeout: 300,
beacon_store: Some("/run/vpncloud.beacon.out".to_string()),
beacon_load: Some("/run/vpncloud.beacon.in".to_string()),
beacon_interval: 7200,
beacon_password: Some("test123".to_string()),
mode: Mode::Normal,
port_forwarding: true,
claims: vec!["10.0.1.0/24".to_string()],
user: Some("nobody".to_string()),
group: Some("nogroup".to_string()),
pid_file: Some("/run/vpncloud.run".to_string()),
stats_file: Some("/var/log/vpncloud.stats".to_string()),
statsd_server: Some("example.com:1234".to_string()),
statsd_prefix: Some("prefix".to_string()),
..Default::default()
prefix: Some("prefix".to_string()),
}),
hook: None,
hooks: HashMap::new(),
});
assert_eq!(
config,
Config {
device_type: Type::Tun,
device_name: "vpncloud%d".to_string(),
device_path: None,
ip: None,
advertise_addresses: vec![],
ifup: Some("ifconfig $IFNAME 10.0.1.1/16 mtu 1400 up".to_string()),
ifdown: Some("true".to_string()),
listen: "3210".to_string(),
peers: vec!["remote.machine.foo:3210".to_string(), "remote.machine.bar:3210".to_string()],
peer_timeout: 600,
keepalive: Some(840),
switch_timeout: 300,
beacon_store: Some("/run/vpncloud.beacon.out".to_string()),
beacon_load: Some("/run/vpncloud.beacon.in".to_string()),
beacon_interval: 7200,
beacon_password: Some("test123".to_string()),
mode: Mode::Normal,
port_forwarding: true,
claims: vec!["10.0.1.0/24".to_string()],
user: Some("nobody".to_string()),
group: Some("nogroup".to_string()),
pid_file: Some("/run/vpncloud.run".to_string()),
stats_file: Some("/var/log/vpncloud.stats".to_string()),
statsd_server: Some("example.com:1234".to_string()),
statsd_prefix: Some("prefix".to_string()),
..Default::default()
}
);
config.merge_args(Args {
type_: Some(Type::Tap),
device: Some("vpncloud0".to_string()),
@ -695,7 +805,7 @@ fn config_merge() {
ifup: Some("ifconfig $IFNAME 10.0.1.2/16 mtu 1400 up".to_string()),
ifdown: Some("ifconfig $IFNAME down".to_string()),
password: Some("anothersecret".to_string()),
listen: Some("3211".to_string()),
listen: Some("[::]:3211".to_string()),
peer_timeout: Some(1801),
keepalive: Some(850),
switch_timeout: Some(301),
@ -716,38 +826,45 @@ fn config_merge() {
group: Some("root".to_string()),
..Default::default()
});
assert_eq!(config, Config {
device_type: Type::Tap,
device_name: "vpncloud0".to_string(),
device_path: Some("/dev/null".to_string()),
fix_rp_filter: false,
ip: None,
ifup: Some("ifconfig $IFNAME 10.0.1.2/16 mtu 1400 up".to_string()),
ifdown: Some("ifconfig $IFNAME down".to_string()),
crypto: CryptoConfig { password: Some("anothersecret".to_string()), ..CryptoConfig::default() },
listen: "[::]:3211".parse::<SocketAddr>().unwrap(),
peers: vec![
"remote.machine.foo:3210".to_string(),
"remote.machine.bar:3210".to_string(),
"another:3210".to_string()
],
peer_timeout: 1801,
keepalive: Some(850),
switch_timeout: 301,
beacon_store: Some("/run/vpncloud.beacon.out2".to_string()),
beacon_load: Some("/run/vpncloud.beacon.in2".to_string()),
beacon_interval: 3600,
beacon_password: Some("test1234".to_string()),
mode: Mode::Switch,
port_forwarding: false,
claims: vec!["10.0.1.0/24".to_string()],
auto_claim: true,
user: Some("root".to_string()),
group: Some("root".to_string()),
pid_file: Some("/run/vpncloud-mynet.run".to_string()),
stats_file: Some("/var/log/vpncloud-mynet.stats".to_string()),
statsd_server: Some("example.com:2345".to_string()),
statsd_prefix: Some("prefix2".to_string()),
daemonize: true
});
assert_eq!(
config,
Config {
device_type: Type::Tap,
device_name: "vpncloud0".to_string(),
device_path: Some("/dev/null".to_string()),
fix_rp_filter: false,
ip: None,
advertise_addresses: vec![],
ifup: Some("ifconfig $IFNAME 10.0.1.2/16 mtu 1400 up".to_string()),
ifdown: Some("ifconfig $IFNAME down".to_string()),
crypto: CryptoConfig { password: Some("anothersecret".to_string()), ..CryptoConfig::default() },
listen: "[::]:3211".to_string(),
peers: vec![
"remote.machine.foo:3210".to_string(),
"remote.machine.bar:3210".to_string(),
"another:3210".to_string()
],
peer_timeout: 1801,
keepalive: Some(850),
switch_timeout: 301,
beacon_store: Some("/run/vpncloud.beacon.out2".to_string()),
beacon_load: Some("/run/vpncloud.beacon.in2".to_string()),
beacon_interval: 3600,
beacon_password: Some("test1234".to_string()),
mode: Mode::Switch,
port_forwarding: false,
claims: vec!["10.0.1.0/24".to_string()],
auto_claim: true,
user: Some("root".to_string()),
group: Some("root".to_string()),
pid_file: Some("/run/vpncloud-mynet.run".to_string()),
stats_file: Some("/var/log/vpncloud-mynet.stats".to_string()),
statsd_server: Some("example.com:2345".to_string()),
statsd_prefix: Some("prefix2".to_string()),
daemonize: true,
hook: None,
hooks: HashMap::new()
}
);
}

507
src/crypto/common.rs Normal file
View File

@ -0,0 +1,507 @@
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 parse_algorithms(algos: &[String]) -> Result<(bool, Vec<&'static aead::Algorithm>), Error> {
let algorithms = algos.iter().map(|a| a as &str).collect::<Vec<_>>();
let allowed = if algorithms.is_empty() { &DEFAULT_ALGORITHMS } else { &algorithms as &[&str] };
let mut algos = vec![];
let mut unencrypted = false;
for name in allowed {
let algo = match &name.to_uppercase() as &str {
"UNENCRYPTED" | "NONE" | "PLAIN" => {
unencrypted = true;
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")),
};
algos.push(algo)
}
Ok((unencrypted, algos))
}
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 (unencrypted, allowed_algos) = Self::parse_algorithms(&config.algorithms)?;
if unencrypted {
warn!("Crypto settings allow unencrypted connections")
}
let mut algos = Algorithms { algorithm_speeds: smallvec![], allow_unencrypted: unencrypted };
let duration = Duration::from_secs_f32(SPEED_TEST_TIME);
let mut speeds = Vec::new();
for algo in allowed_algos {
let speed = test_speed(algo, &duration);
algos.algorithm_speeds.push((algo, speed as f32));
speeds.push((format!("{:?}", algo), 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 public_key_from_private_key(privkey: &str) -> Result<String, Error> {
let keypair = Self::parse_private_key(privkey)?;
Ok(to_base62(keypair.public_key().as_ref()))
}
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),
}
}
}
}

View File

@ -1,62 +1,64 @@
//! 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
//! scope of the crypto core. The crypto core assumes that the remote node will always have the necessary key to decrypt
//! the message.
//!
//! The crypto core encrypts messages in place, writes some extra data (key id and nonce) into a given space and
//! includes the given header data in the authentication tag. When decrypting messages, the crypto core reads the extra
//! data, uses the key id to find the right key to decrypting the message and then decrypts the message, using the given
//! nonce and including the given header data in the verification of the authentication tag.
//!
//! While the core only uses a single key at a time for encrypting messages, it is ready to decrypt messages based on
//! one of 4 stored keys (the encryption key being one of them). An external key rotation is responsible for adding the
//! key to the remote peer before switching to the key on the local peer for encryption.
//!
//! As mentioned, the encryption and decryption works in place. Therefore the parameter payload_and_tag contains (when
//! decrypting) or provides space for (when encrypting) the payload and the authentication tag. When encrypting, that
//! means, that the last TAG_LEN bytes of payload_and_tag must be reserved for the tag and must not contain payload
//! bytes.
//!
//! The nonce is a value of 12 bytes (192 bits). Since both nodes can use the same key for encryption, the most
//! significant byte (msb) of the nonce is initialized differently on both peers: one peer uses the value 0x00 and the
//! other one 0x80. That means that the nonce space is essentially divided in two halves, one for each node.
//!
//! To save space and keep the encrypted data aligned to 64 bits, not all bytes of the nonce are transferred. Instead,
//! only 7 bytes are included in messages (another byte is used for the key id, hence 64 bit alignment). The rest of the
//! nonce is deduced by the nodes: All other bytes are assumed to be 0x00, except for the most significant byte, which
//! is assumed to be the opposite ones own msb. This has two nice effects:
//! 1) Long before the nonce could theoretically repeat, the messages can no longer be decrypted by the peer as the
//! higher bytes are no longer zero as assumed.
//! 2) By deducing the msb to be the opposite of ones own msb, it is no longer possible for an attacker to redirect a
//! message back to the sender because then the assumed nonce will be wrong and the message fails to decrypt. Otherwise,
//! this could lead to problems as nodes would be able to accidentally decrypt their own messages.
//!
//! In order to be resistent against replay attacks but allow for reordering of messages, the crypto core uses nonce
//! pinning. For every active key, the biggest nonce seen so far is being tracked. Every second, the biggest nonce seen
//! one second ago plus 1 becomes the minimum nonce that is accepted for that key. That means, that reordering can
//! happen within one second but after a second, old messages will not be accepted anymore.
// 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
// scope of the crypto core. The crypto core assumes that the remote node will always have the necessary key to decrypt
// the message.
//
// The crypto core encrypts messages in place, writes some extra data (key id and nonce) into a given space and
// includes the given header data in the authentication tag. When decrypting messages, the crypto core reads the extra
// data, uses the key id to find the right key to decrypting the message and then decrypts the message, using the given
// nonce and including the given header data in the verification of the authentication tag.
//
// While the core only uses a single key at a time for encrypting messages, it is ready to decrypt messages based on
// one of 4 stored keys (the encryption key being one of them). An external key rotation is responsible for adding the
// key to the remote peer before switching to the key on the local peer for encryption.
//
// As mentioned, the encryption and decryption works in place. Therefore the parameter payload_and_tag contains (when
// decrypting) or provides space for (when encrypting) the payload and the authentication tag. When encrypting, that
// means, that the last TAG_LEN bytes of payload_and_tag must be reserved for the tag and must not contain payload
// bytes.
//
// The nonce is a value of 12 bytes (192 bits). Since both nodes can use the same key for encryption, the most
// significant byte (msb) of the nonce is initialized differently on both peers: one peer uses the value 0x00 and the
// other one 0x80. That means that the nonce space is essentially divided in two halves, one for each node.
//
// To save space and keep the encrypted data aligned to 64 bits, not all bytes of the nonce are transferred. Instead,
// only 7 bytes are included in messages (another byte is used for the key id, hence 64 bit alignment). The rest of the
// nonce is deduced by the nodes: All other bytes are assumed to be 0x00, except for the most significant byte, which
// is assumed to be the opposite ones own msb. This has two nice effects:
// 1) Long before the nonce could theoretically repeat, the messages can no longer be decrypted by the peer as the
// higher bytes are no longer zero as assumed.
// 2) By deducing the msb to be the opposite of ones own msb, it is no longer possible for an attacker to redirect a
// message back to the sender because then the assumed nonce will be wrong and the message fails to decrypt. Otherwise,
// this could lead to problems as nodes would be able to accidentally decrypt their own messages.
//
// In order to be resistent against replay attacks but allow for reordering of messages, the crypto core uses nonce
// pinning. For every active key, the biggest nonce seen so far is being tracked. Every second, the biggest nonce seen
// one second ago plus 1 becomes the minimum nonce that is accepted for that key. That means, that reordering can
// happen within one second but after a second, old messages will not be accepted anymore.
use byteorder::{ReadBytesExt, WriteBytesExt};
use ring::{
aead::{self, LessSafeKey, UnboundKey},
rand::{SecureRandom, SystemRandom}
rand::{SecureRandom, SystemRandom},
};
use std::{
io::{Cursor, Read, Write},
mem,
time::{Duration, Instant}
time::{Duration, Instant},
};
use super::{Error, MsgBuffer};
use crate::{error::Error, util::MsgBuffer};
const NONCE_LEN: usize = 12;
pub const TAG_LEN: usize = 16;
pub const EXTRA_LEN: usize = 8;
fn random_data(size: usize) -> Vec<u8> {
let rand = SystemRandom::new();
let mut data = vec![0; size];
@ -92,7 +94,7 @@ impl Nonce {
num = num.wrapping_add(1);
self.0[i] = num;
if num > 0 {
return
return;
}
}
}
@ -103,19 +105,19 @@ struct CryptoKey {
send_nonce: Nonce,
min_nonce: Nonce,
next_min_nonce: Nonce,
seen_nonce: Nonce
seen_nonce: Nonce,
}
impl CryptoKey {
fn new(rand: &SystemRandom, key: LessSafeKey, nonce_half: bool) -> Self {
let mut send_nonce = Nonce::random(&rand);
let mut send_nonce = Nonce::random(rand);
send_nonce.set_msb(if nonce_half { 0x80 } else { 0x00 });
CryptoKey {
key,
send_nonce,
min_nonce: Nonce::zero(),
next_min_nonce: Nonce::zero(),
seen_nonce: Nonce::zero()
seen_nonce: Nonce::zero(),
}
}
@ -126,12 +128,11 @@ impl CryptoKey {
}
}
pub struct CryptoCore {
rand: SystemRandom,
keys: [CryptoKey; 4],
current_key: usize,
nonce_half: bool
nonce_half: bool,
}
impl CryptoCore {
@ -146,11 +147,11 @@ impl CryptoCore {
CryptoKey::new(&rand, key, nonce_half),
CryptoKey::new(&rand, dummy_key1, nonce_half),
CryptoKey::new(&rand, dummy_key2, nonce_half),
CryptoKey::new(&rand, dummy_key3, nonce_half)
CryptoKey::new(&rand, dummy_key3, nonce_half),
],
current_key: 0,
nonce_half,
rand
rand,
}
}
@ -176,7 +177,7 @@ impl CryptoCore {
fn decrypt_with_key(key: &mut CryptoKey, nonce: Nonce, data_and_tag: &mut [u8]) -> Result<(), Error> {
if nonce < key.min_nonce {
return Err(Error::Crypto("Old nonce rejected"))
return Err(Error::Crypto("Old nonce rejected"));
}
// decrypt
let crypto_nonce = aead::Nonce::assume_unique_for_key(*nonce.as_bytes());
@ -230,7 +231,6 @@ impl CryptoCore {
}
}
pub fn create_dummy_pair(algo: &'static aead::Algorithm) -> (CryptoCore, CryptoCore) {
let key_data = random_data(algo.key_len());
let sender = CryptoCore::new(LessSafeKey::new(UnboundKey::new(algo, &key_data).unwrap()), true);
@ -256,7 +256,6 @@ pub fn test_speed(algo: &'static aead::Algorithm, max_time: &Duration) -> f64 {
data as f64 / duration / 1_000_000.0
}
#[cfg(test)]
mod tests {
use super::*;
@ -299,7 +298,6 @@ mod tests {
test_encrypt_decrypt(&aead::CHACHA20_POLY1305)
}
fn test_tampering(algo: &'static aead::Algorithm) {
let (mut sender, mut receiver) = create_dummy_pair(algo);
let plain = random_data(1000);
@ -430,7 +428,6 @@ mod tests {
test_key_rotation(&aead::CHACHA20_POLY1305);
}
#[test]
fn test_core_size() {
assert_eq!(2384, mem::size_of::<CryptoCore>());
@ -454,37 +451,3 @@ mod tests {
assert!(speed > 10.0);
}
}
#[cfg(feature = "bench")]
mod benches {
use super::*;
use test::Bencher;
fn crypto_bench(b: &mut Bencher, algo: &'static aead::Algorithm) {
let mut buffer = MsgBuffer::new(EXTRA_LEN);
buffer.set_length(1400);
let (mut sender, mut receiver) = create_dummy_pair(algo);
b.iter(|| {
sender.encrypt(&mut buffer);
receiver.decrypt(&mut buffer).unwrap();
});
b.bytes = 1400;
}
#[bench]
fn crypto_chacha20(b: &mut Bencher) {
crypto_bench(b, &aead::CHACHA20_POLY1305)
}
#[bench]
fn crypto_aes128(b: &mut Bencher) {
crypto_bench(b, &aead::AES_128_GCM)
}
#[bench]
fn crypto_aes256(b: &mut Bencher) {
crypto_bench(b, &aead::AES_256_GCM)
}
}

View File

@ -1,78 +1,80 @@
//! 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
//! and a set of supported crypto algorithms as well as the expected speed when using them. If successful, the handshake
//! will negotiate a crypto algorithm to use and a common ephemeral symmetric key and exchange a given payload between
//! the nodes.
//!
//! The handshake consists of 3 stages, "ping", "pong" and "peng". In the following description, the node that initiates
//! the connection is named "A" and the other node is named "B". Since a lot of things are going on in parallel in the
//! handshake, those aspects are described separately in the following paragraphs.
//!
//! Every message contains the node id of the sender. If a node receives a message with its own node id, it just ignores
//! it and closes the connection. This is the way nodes avoid to connect to themselves as it is not trivial for a node
//! to know its own addresses (especially in the case of NAT).
//!
//! All initialization messages are signed by the asymmetric key of the sender. Also the messages indicate the public
//! key being used, so the receiver can use the correct public key to verify the signature. The public key itself is not
//! attached to the message for privacy reasons (the public key is stable over multiple restarts while the node id is
//! only valid for a single run). Instead, a 2 byte salt value as well as the last 2 bytes of the salted sha 2 hash of
//! the public key are used to identify the public key. This way, a receiver that trusts this public key can identify
//! it but a random observer can't. If the public key is unknown or the signature can't be verified, the message is
//! ignored.
//!
//! Every message contains a byte that specifies the stage (ping = 1, pong = 2, peng = 3). If a message with an
//! unexpected stage is received, it is ignored and the last message that has been sent is repeated. There is only one
//! exception to this rule: if a "pong" message is expected, but a "ping" message is received instead AND the node id of
//! the sender is greater than the node id of the receiver, the receiving node will reset its state and assume the role
//! of a receiver of the initialization (i.e. "B"). This is used to "negotiate" the roles A and B when both nodes
//! initiate the connection in parallel and think they are A.
//!
//! Upon connection creation, both nodes create a random ephemeral ECDH key pair and exchange the public keys in the
//! ping and pong messages. A sends the ping message to B containing A's public key and B replies with a pong message
//! containing B's public key. That means, that after receiving the ping message B can calculate the shared key material
//! and after receiving the pong message A can calculate the shared key material.
//!
//! The ping message and the pong message contain a set of supported crypto algorithms together with the estimated
//! speeds of the algorithms. When B receives a ping message, or A receives a pong message, it can combine this
//! information with its own algorithm list and select the algorithm with the best expected speed for the crypto core.
//!
//! The pong and peng message contain the payload that the nodes want to exchange in the initialization phase apart from
//! the cryptographic initialization. This payload is encoded according to the application and encrypted using the key
//! material and the crypto algorithm that have been negotiated via the ping and pong messages. The pong message,
//! therefore contains information to set up symmetric encryption as well as a part that is already encrypted.
//!
//! The handshake ends for A after sending the peng message and for B after receiving this message. At this time both
//! nodes initialize the connection using the payload and enter normal operation. The negotiated crypto core is used for
//! future communication and the key rotation is started. Since the peng message can be lost, A needs to keep the
//! initialization state in order to repeat a lost peng message. After one second, A removes that state.
//!
//! Once every second, both nodes check whether they have already finished the initialization. If not, they repeat their
//! last message. After 5 seconds, the initialization is aborted as failed.
// 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
// and a set of supported crypto algorithms as well as the expected speed when using them. If successful, the handshake
// will negotiate a crypto algorithm to use and a common ephemeral symmetric key and exchange a given payload between
// the nodes.
//
// The handshake consists of 3 stages, "ping", "pong" and "peng". In the following description, the node that initiates
// the connection is named "A" and the other node is named "B". Since a lot of things are going on in parallel in the
// handshake, those aspects are described separately in the following paragraphs.
//
// Every message contains the node id of the sender. If a node receives a message with its own node id, it just ignores
// it and closes the connection. This is the way nodes avoid to connect to themselves as it is not trivial for a node
// to know its own addresses (especially in the case of NAT).
//
// All initialization messages are signed by the asymmetric key of the sender. Also the messages indicate the public
// key being used, so the receiver can use the correct public key to verify the signature. The public key itself is not
// attached to the message for privacy reasons (the public key is stable over multiple restarts while the node id is
// only valid for a single run). Instead, a 2 byte salt value as well as the last 2 bytes of the salted sha 2 hash of
// the public key are used to identify the public key. This way, a receiver that trusts this public key can identify
// it but a random observer can't. If the public key is unknown or the signature can't be verified, the message is
// ignored.
//
// Every message contains a byte that specifies the stage (ping = 1, pong = 2, peng = 3). If a message with an
// unexpected stage is received, it is ignored and the last message that has been sent is repeated. There is only one
// exception to this rule: if a "pong" message is expected, but a "ping" message is received instead AND the node id of
// the sender is greater than the node id of the receiver, the receiving node will reset its state and assume the role
// of a receiver of the initialization (i.e. "B"). This is used to "negotiate" the roles A and B when both nodes
// initiate the connection in parallel and think they are A.
//
// Upon connection creation, both nodes create a random ephemeral ECDH key pair and exchange the public keys in the
// ping and pong messages. A sends the ping message to B containing A's public key and B replies with a pong message
// containing B's public key. That means, that after receiving the ping message B can calculate the shared key material
// and after receiving the pong message A can calculate the shared key material.
//
// The ping message and the pong message contain a set of supported crypto algorithms together with the estimated
// speeds of the algorithms. When B receives a ping message, or A receives a pong message, it can combine this
// information with its own algorithm list and select the algorithm with the best expected speed for the crypto core.
//
// The pong and peng message contain the payload that the nodes want to exchange in the initialization phase apart from
// the cryptographic initialization. This payload is encoded according to the application and encrypted using the key
// material and the crypto algorithm that have been negotiated via the ping and pong messages. The pong message,
// therefore contains information to set up symmetric encryption as well as a part that is already encrypted.
//
// The handshake ends for A after sending the peng message and for B after receiving this message. At this time both
// nodes initialize the connection using the payload and enter normal operation. The negotiated crypto core is used for
// future communication and the key rotation is started. Since the peng message can be lost, A needs to keep the
// initialization state in order to repeat a lost peng message. After one second, A removes that state.
//
// Once every second, both nodes check whether they have already finished the initialization. If not, they repeat their
// last message. After 5 seconds, the initialization is aborted as failed.
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},
agreement::{agree_ephemeral, X25519},
digest,
rand::{SecureRandom, SystemRandom},
signature::{self, Ed25519KeyPair, KeyPair, ED25519, ED25519_PUBLIC_KEY_LEN}
signature::{self, Ed25519KeyPair, KeyPair, ED25519, ED25519_PUBLIC_KEY_LEN},
};
use smallvec::{smallvec, SmallVec};
use std::{
cmp, f32,
fmt::Debug,
io::{self, Cursor, Read, Write},
sync::Arc
sync::Arc,
};
pub const STAGE_PING: u8 = 1;
pub const STAGE_PONG: u8 = 2;
pub const STAGE_PENG: u8 = 3;
@ -84,24 +86,23 @@ pub const MAX_FAILED_RETRIES: usize = 120;
pub const SALTED_NODE_ID_HASH_LEN: usize = 20;
pub type SaltedNodeIdHash = [u8; SALTED_NODE_ID_HASH_LEN];
#[allow(clippy::large_enum_variant)]
pub enum InitMsg {
Ping {
salted_node_id_hash: SaltedNodeIdHash,
ecdh_public_key: EcdhPublicKey,
algorithms: Algorithms
algorithms: Algorithms,
},
Pong {
salted_node_id_hash: SaltedNodeIdHash,
ecdh_public_key: EcdhPublicKey,
algorithms: Algorithms,
encrypted_payload: MsgBuffer
encrypted_payload: MsgBuffer,
},
Peng {
salted_node_id_hash: SaltedNodeIdHash,
encrypted_payload: MsgBuffer
}
encrypted_payload: MsgBuffer,
},
}
impl InitMsg {
@ -116,7 +117,7 @@ impl InitMsg {
match self {
InitMsg::Ping { .. } => STAGE_PING,
InitMsg::Pong { .. } => STAGE_PONG,
InitMsg::Peng { .. } => STAGE_PENG
InitMsg::Peng { .. } => STAGE_PENG,
}
}
@ -124,7 +125,7 @@ impl InitMsg {
match self {
InitMsg::Ping { salted_node_id_hash, .. }
| InitMsg::Pong { salted_node_id_hash, .. }
| InitMsg::Peng { salted_node_id_hash, .. } => salted_node_id_hash
| InitMsg::Peng { salted_node_id_hash, .. } => salted_node_id_hash,
}
}
@ -151,11 +152,11 @@ impl InitMsg {
if Self::calculate_hash(tk, &public_key_salt) == public_key_hash {
public_key_data.clone_from_slice(tk);
found_key = true;
break
break;
}
}
if !found_key {
return Err(Error::Crypto("untrusted peer"))
return Err(Error::Crypto("untrusted peer"));
}
let mut stage = None;
@ -167,19 +168,19 @@ impl InitMsg {
loop {
let field = r.read_u8().map_err(|_| Error::Parse("Init message too short"))?;
if field == Self::PART_END {
break
break;
}
let field_len = r.read_u16::<NetworkEndian>().map_err(|_| Error::Parse("Init message too short"))? as usize;
match field {
Self::PART_STAGE => {
if field_len != 1 {
return Err(Error::CryptoInit("Invalid size for stage field"))
return Err(Error::CryptoInit("Invalid size for stage field"));
}
stage = Some(r.read_u8().map_err(|_| Error::Parse("Init message too short"))?)
}
Self::PART_SALTED_NODE_ID_HASH => {
if field_len != SALTED_NODE_ID_HASH_LEN {
return Err(Error::CryptoInit("Invalid size for salted node id hash field"))
return Err(Error::CryptoInit("Invalid size for salted node id hash field"));
}
let mut id = [0; SALTED_NODE_ID_HASH_LEN];
r.read_exact(&mut id).map_err(|_| Error::Parse("Init message too short"))?;
@ -209,7 +210,7 @@ impl InitMsg {
1 => Some(&AES_128_GCM),
2 => Some(&AES_256_GCM),
3 => Some(&CHACHA20_POLY1305),
_ => None
_ => None,
};
let speed =
r.read_f32::<NetworkEndian>().map_err(|_| Error::Parse("Init message too short"))?;
@ -234,54 +235,54 @@ impl InitMsg {
let signed_data = &r.into_inner()[0..pos];
let public_key = signature::UnparsedPublicKey::new(&ED25519, &public_key_data);
if public_key.verify(&signed_data, &signature).is_err() {
return Err(Error::Crypto("invalid signature"))
if public_key.verify(signed_data, &signature).is_err() {
return Err(Error::Crypto("invalid signature"));
}
let stage = match stage {
Some(val) => val,
None => return Err(Error::CryptoInit("Init message without stage"))
None => return Err(Error::CryptoInit("Init message without stage")),
};
let salted_node_id_hash = match salted_node_id_hash {
Some(val) => val,
None => return Err(Error::CryptoInit("Init message without node id"))
None => return Err(Error::CryptoInit("Init message without node id")),
};
let msg = match stage {
STAGE_PING => {
let ecdh_public_key = match ecdh_public_key {
Some(val) => val,
None => return Err(Error::CryptoInit("Init message without ecdh public key"))
None => return Err(Error::CryptoInit("Init message without ecdh public key")),
};
let algorithms = match algorithms {
Some(val) => val,
None => return Err(Error::CryptoInit("Init message without algorithms"))
None => return Err(Error::CryptoInit("Init message without algorithms")),
};
Self::Ping { salted_node_id_hash, ecdh_public_key, algorithms }
}
STAGE_PONG => {
let ecdh_public_key = match ecdh_public_key {
Some(val) => val,
None => return Err(Error::CryptoInit("Init message without ecdh public key"))
None => return Err(Error::CryptoInit("Init message without ecdh public key")),
};
let algorithms = match algorithms {
Some(val) => val,
None => return Err(Error::CryptoInit("Init message without algorithms"))
None => return Err(Error::CryptoInit("Init message without algorithms")),
};
let encrypted_payload = match encrypted_payload {
Some(val) => val,
None => return Err(Error::CryptoInit("Init message without payload"))
None => return Err(Error::CryptoInit("Init message without payload")),
};
Self::Pong { salted_node_id_hash, ecdh_public_key, algorithms, encrypted_payload }
}
STAGE_PENG => {
let encrypted_payload = match encrypted_payload {
Some(val) => val,
None => return Err(Error::CryptoInit("Init message without payload"))
None => return Err(Error::CryptoInit("Init message without payload")),
};
Self::Peng { salted_node_id_hash, encrypted_payload }
}
_ => return Err(Error::CryptoInit("Invalid stage"))
_ => return Err(Error::CryptoInit("Invalid stage")),
};
Ok((msg, public_key_data))
@ -318,9 +319,9 @@ impl InitMsg {
w.write_u8(Self::PART_ECDH_PUBLIC_KEY)?;
let key_bytes = ecdh_public_key.bytes();
w.write_u16::<NetworkEndian>(key_bytes.len() as u16)?;
w.write_all(&key_bytes)?;
w.write_all(key_bytes)?;
}
_ => ()
_ => (),
}
match &self {
@ -348,7 +349,7 @@ impl InitMsg {
w.write_f32::<NetworkEndian>(*speed)?;
}
}
_ => ()
_ => (),
}
match &self {
@ -357,7 +358,7 @@ impl InitMsg {
w.write_u16::<NetworkEndian>(encrypted_payload.len() as u16)?;
w.write_all(encrypted_payload.message())?;
}
_ => ()
_ => (),
}
w.write_u8(Self::PART_END)?;
@ -371,14 +372,12 @@ impl InitMsg {
}
}
#[derive(PartialEq, Debug)]
pub enum InitResult<P: Payload> {
Continue,
Success { peer_payload: P, is_initiator: bool }
Success { peer_payload: P, is_initiator: bool },
}
pub struct InitState<P: Payload> {
node_id: NodeId,
salted_node_id_hash: SaltedNodeIdHash,
@ -391,16 +390,16 @@ pub struct InitState<P: Payload> {
last_message: Option<Vec<u8>>,
crypto: Option<CryptoCore>,
algorithms: Algorithms,
#[allow(dead_code)] // Used in tests
selected_algorithm: Option<&'static Algorithm>,
failed_retries: usize
failed_retries: usize,
}
impl<P: Payload> InitState<P> {
pub fn new(
node_id: NodeId, payload: P, key_pair: Arc<Ed25519KeyPair>, trusted_keys: Arc<[Ed25519PublicKey]>,
algorithms: Algorithms
) -> Self
{
algorithms: Algorithms,
) -> Self {
let mut hash = [0; SALTED_NODE_ID_HASH_LEN];
let rng = SystemRandom::new();
rng.fill(&mut hash[0..4]).unwrap();
@ -420,7 +419,7 @@ impl<P: Payload> InitState<P> {
selected_algorithm: None,
algorithms,
failed_retries: 0,
close_time: 60
close_time: 60,
}
}
@ -460,8 +459,8 @@ impl<P: Payload> InitState<P> {
}
fn derive_master_key(&self, algo: &'static Algorithm, privk: EcdhPrivateKey, pubk: &EcdhPublicKey) -> LessSafeKey {
agree_ephemeral(privk, pubk, (), |k| {
UnboundKey::new(algo, &k[..algo.key_len()]).map(LessSafeKey::new).map_err(|_| ())
agree_ephemeral(privk, pubk, |k| {
UnboundKey::new(algo, &k[..algo.key_len()]).map(LessSafeKey::new).unwrap()
})
.unwrap()
}
@ -489,7 +488,7 @@ impl<P: Payload> InitState<P> {
if let Some(crypto) = &mut self.crypto {
crypto.decrypt(data)?;
}
Ok(P::read_from(Cursor::new(data.message()))?)
P::read_from(Cursor::new(data.message()))
}
fn check_salted_node_id_hash(&self, hash: &SaltedNodeIdHash, node_id: NodeId) -> bool {
@ -506,31 +505,25 @@ impl<P: Payload> InitState<P> {
let mut public_key = [0; ED25519_PUBLIC_KEY_LEN];
public_key.clone_from_slice(self.key_pair.as_ref().public_key().as_ref());
let msg = match stage {
STAGE_PING => {
InitMsg::Ping {
salted_node_id_hash: self.salted_node_id_hash,
ecdh_public_key: ecdh_public_key.unwrap(),
algorithms: self.algorithms.clone()
}
}
STAGE_PONG => {
InitMsg::Pong {
salted_node_id_hash: self.salted_node_id_hash,
ecdh_public_key: ecdh_public_key.unwrap(),
algorithms: self.algorithms.clone(),
encrypted_payload: self.encrypt_payload()
}
}
STAGE_PENG => {
InitMsg::Peng {
salted_node_id_hash: self.salted_node_id_hash,
encrypted_payload: self.encrypt_payload()
}
}
_ => unreachable!()
STAGE_PING => InitMsg::Ping {
salted_node_id_hash: self.salted_node_id_hash,
ecdh_public_key: ecdh_public_key.unwrap(),
algorithms: self.algorithms.clone(),
},
STAGE_PONG => InitMsg::Pong {
salted_node_id_hash: self.salted_node_id_hash,
ecdh_public_key: ecdh_public_key.unwrap(),
algorithms: self.algorithms.clone(),
encrypted_payload: self.encrypt_payload(),
},
STAGE_PENG => InitMsg::Peng {
salted_node_id_hash: self.salted_node_id_hash,
encrypted_payload: self.encrypt_payload(),
},
_ => unreachable!(),
};
let mut bytes = out.buffer();
let len = msg.write_to(&mut bytes, &self.key_pair).expect("Buffer too small");
let bytes = out.buffer();
let len = msg.write_to(bytes, &self.key_pair).expect("Buffer too small");
self.last_message = Some(bytes[0..len].to_vec());
out.set_length(len);
}
@ -546,7 +539,7 @@ impl<P: Payload> InitState<P> {
fn select_algorithm(&self, peer_algos: &Algorithms) -> Result<Option<(&'static Algorithm, f32)>, Error> {
if self.algorithms.allow_unencrypted && peer_algos.allow_unencrypted {
return Ok(None)
return Ok(None);
}
// For each supported algorithm, find the algorithm in the list of the peer (ignore algorithm if not found).
// Take the minimal speed reported by either us or the peer.
@ -580,7 +573,7 @@ impl<P: Payload> InitState<P> {
if self.salted_node_id_hash == salted_node_id_hash
|| self.check_salted_node_id_hash(&salted_node_id_hash, self.node_id)
{
return Err(Error::CryptoInitFatal("Connected to self"))
return Err(Error::CryptoInitFatal("Connected to self"));
}
if stage != self.next_stage {
if self.next_stage == STAGE_PONG && stage == STAGE_PING {
@ -592,15 +585,15 @@ impl<P: Payload> InitState<P> {
self.last_message = None;
self.ecdh_private_key = None;
} else {
return Ok(InitResult::Continue)
return Ok(InitResult::Continue);
}
} else if self.next_stage == CLOSING {
return Ok(InitResult::Continue)
return Ok(InitResult::Continue);
} else if self.last_message.is_some() {
self.repeat_last_message(out);
return Ok(InitResult::Continue)
return Ok(InitResult::Continue);
} else {
return Err(Error::CryptoInitFatal("Received invalid stage as first message"))
return Err(Error::CryptoInitFatal("Received invalid stage as first message"));
}
}
self.failed_retries = 0;
@ -662,7 +655,6 @@ impl<P: Payload> InitState<P> {
}
}
#[cfg(test)]
mod tests {
use super::*;
@ -670,7 +662,7 @@ mod tests {
impl Payload for Vec<u8> {
fn write_to(&self, buffer: &mut MsgBuffer) {
buffer.buffer().write_all(&self).expect("Buffer too small");
buffer.buffer().write_all(self).expect("Buffer too small");
buffer.set_length(self.len())
}
@ -694,7 +686,7 @@ mod tests {
rng.fill(&mut node2).unwrap();
let algorithms = Algorithms {
algorithm_speeds: smallvec![(&AES_128_GCM, 600.0), (&AES_256_GCM, 500.0), (&CHACHA20_POLY1305, 400.0)],
allow_unencrypted: false
allow_unencrypted: false,
};
let sender = InitState::new(node1, vec![1], key_pair.clone(), trusted_nodes.clone(), algorithms.clone());
let receiver = InitState::new(node2, vec![2], key_pair, trusted_nodes, algorithms);
@ -714,12 +706,12 @@ mod tests {
assert_eq!(sender.stage(), WAITING_TO_CLOSE);
let result = match result {
InitResult::Success { .. } => receiver.handle_init(&mut out).unwrap(),
InitResult::Continue => unreachable!()
InitResult::Continue => unreachable!(),
};
assert_eq!(receiver.stage(), CLOSING);
match result {
InitResult::Success { .. } => assert!(out.is_empty()),
InitResult::Continue => unreachable!()
InitResult::Continue => unreachable!(),
}
}
@ -745,14 +737,14 @@ mod tests {
// lost peng, sender recovers
out.clear();
}
InitResult::Continue => unreachable!()
InitResult::Continue => unreachable!(),
};
sender.every_second(&mut out).unwrap();
let result = receiver.handle_init(&mut out).unwrap();
assert_eq!(receiver.stage(), CLOSING);
match result {
InitResult::Success { .. } => assert!(out.is_empty()),
InitResult::Continue => unreachable!()
InitResult::Continue => unreachable!(),
}
}
@ -776,7 +768,7 @@ mod tests {
// lost peng, sender recovers
out.clear();
}
InitResult::Continue => unreachable!()
InitResult::Continue => unreachable!(),
};
receiver.every_second(&mut out).unwrap();
sender.handle_init(&mut out).unwrap();
@ -784,7 +776,7 @@ mod tests {
assert_eq!(receiver.stage(), CLOSING);
match result {
InitResult::Success { .. } => assert!(out.is_empty()),
InitResult::Continue => unreachable!()
InitResult::Continue => unreachable!(),
}
}
@ -833,7 +825,7 @@ mod tests {
}
fn test_algorithm_negotiation(
algos1: Algorithms, algos2: Algorithms, success: bool, selected: Option<&'static Algorithm>
algos1: Algorithms, algos2: Algorithms, success: bool, selected: Option<&'static Algorithm>,
) {
let (mut sender, mut receiver) = create_pair();
sender.algorithms = algos1;
@ -843,7 +835,7 @@ mod tests {
let res = receiver.handle_init(&mut out);
assert_eq!(res.is_ok(), success);
if !success {
return
return;
}
sender.handle_init(&mut out).unwrap();
receiver.handle_init(&mut out).unwrap();
@ -857,70 +849,70 @@ mod tests {
test_algorithm_negotiation(
Algorithms {
algorithm_speeds: smallvec![(&AES_128_GCM, 600.0), (&AES_256_GCM, 500.0), (&CHACHA20_POLY1305, 400.0)],
allow_unencrypted: false
allow_unencrypted: false,
},
Algorithms {
algorithm_speeds: smallvec![(&AES_128_GCM, 600.0), (&AES_256_GCM, 500.0), (&CHACHA20_POLY1305, 400.0)],
allow_unencrypted: false
allow_unencrypted: false,
},
true,
Some(&AES_128_GCM)
Some(&AES_128_GCM),
);
// Overlapping but different
test_algorithm_negotiation(
Algorithms {
algorithm_speeds: smallvec![(&AES_256_GCM, 500.0), (&CHACHA20_POLY1305, 400.0)],
allow_unencrypted: false
allow_unencrypted: false,
},
Algorithms {
algorithm_speeds: smallvec![(&AES_128_GCM, 600.0), (&AES_256_GCM, 500.0)],
allow_unencrypted: false
allow_unencrypted: false,
},
true,
Some(&AES_256_GCM)
Some(&AES_256_GCM),
);
// Select fastest pair
test_algorithm_negotiation(
Algorithms {
algorithm_speeds: smallvec![(&AES_128_GCM, 600.0), (&AES_256_GCM, 500.0), (&CHACHA20_POLY1305, 400.0)],
allow_unencrypted: false
allow_unencrypted: false,
},
Algorithms {
algorithm_speeds: smallvec![(&AES_128_GCM, 40.0), (&AES_256_GCM, 50.0), (&CHACHA20_POLY1305, 60.0)],
allow_unencrypted: false
allow_unencrypted: false,
},
true,
Some(&CHACHA20_POLY1305)
Some(&CHACHA20_POLY1305),
);
// Select unencrypted if supported by both
test_algorithm_negotiation(
Algorithms {
algorithm_speeds: smallvec![(&AES_128_GCM, 600.0), (&AES_256_GCM, 500.0), (&CHACHA20_POLY1305, 400.0)],
allow_unencrypted: true
allow_unencrypted: true,
},
Algorithms {
algorithm_speeds: smallvec![(&AES_128_GCM, 600.0), (&AES_256_GCM, 500.0), (&CHACHA20_POLY1305, 400.0)],
allow_unencrypted: true
allow_unencrypted: true,
},
true,
None
None,
);
// Do not select unencrypted if only supported by one
test_algorithm_negotiation(
Algorithms {
algorithm_speeds: smallvec![(&AES_128_GCM, 600.0), (&AES_256_GCM, 500.0), (&CHACHA20_POLY1305, 400.0)],
allow_unencrypted: true
allow_unencrypted: true,
},
Algorithms {
algorithm_speeds: smallvec![(&AES_128_GCM, 600.0), (&AES_256_GCM, 500.0), (&CHACHA20_POLY1305, 400.0)],
allow_unencrypted: false
allow_unencrypted: false,
},
true,
Some(&AES_128_GCM)
Some(&AES_128_GCM),
);
// Fail if no match
@ -928,10 +920,10 @@ mod tests {
Algorithms { algorithm_speeds: smallvec![(&AES_128_GCM, 600.0)], allow_unencrypted: true },
Algorithms {
algorithm_speeds: smallvec![(&AES_256_GCM, 500.0), (&CHACHA20_POLY1305, 400.0)],
allow_unencrypted: false
allow_unencrypted: false,
},
false,
Some(&AES_128_GCM)
Some(&AES_128_GCM),
);
}
}

View File

@ -1,497 +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 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> {
if self.unencrypted {
return Ok(())
}
self.get_core()?.decrypt(buffer)
}
pub fn handle_message(&mut self, buffer: &mut MsgBuffer) -> Result<MessageResult<P>, Error> {
if buffer.is_empty() {
return Err(Error::InvalidCryptoState("No message in buffer"))
}
if is_init_message(buffer.buffer()) {
debug!("Received init message");
buffer.take_prefix();
self.handle_init_message(buffer)
} else {
debug!("Received encrypted message");
self.decrypt_message(buffer)?;
let msg_type = buffer.take_prefix();
if msg_type == MESSAGE_TYPE_ROTATION {
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> {
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 {
!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)
}
}
}
}
pub use common::*;

View File

@ -1,48 +1,51 @@
//! 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
//! common key material. There are always two separate ecdh handshakes going on: one initiated by each peer.
//! However, one handshake is always one step ahead of the other. That means that every message being sent contains a
//! public key from step 1 of the handshake "proposed key" and a public key from step 2 of the handshake "confirmed
//! key" (all messages except first message).
//!
//! When receiving a message from the peer, the node will create a new ecdh key pair and perform the key
//! calculation for the proposed key. The peer will store the public key for the confirmation as pending to be
//! confirmed in the next cycle. Also, if the message contains a confirmation (all but the very first message do),
//! the node will use the stored private key to perform the ecdh key calculation and emit that key to be used in
//! the crypto stream.
//!
//! Upon each cycle, a node first checks if it still has a proposed key that has not been confirmed by the remote
//! peer. If so, a message must have been lost and the whole last message including the proposed key as well as the
//! last confirmed key is being resent. If no proposed key is stored, the node will create a new ecdh key pair, and
//! store the private key as proposed key. It then sends out a message containing the public key as proposal, as
//! well as confirming the pending key. This key is also emitted to be added to the crypto stream but not to be
//! used for encrypting.
//!
//! Monotonically increasing message ids guard the communication from message duplication and also serve as
//! identifiers for the keys to be used in the crypto stream. Since the keys are rotating, the last 2 bits of the
//! id are enough to identify the key.
//!
//! The whole communication is sent via the crypto stream and is therefore encrypted and protected against tampering.
// 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::{Error, Key, MsgBuffer};
// 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
// common key material. There are always two separate ecdh handshakes going on: one initiated by each peer.
// However, one handshake is always one step ahead of the other. That means that every message being sent contains a
// public key from step 1 of the handshake "proposed key" and a public key from step 2 of the handshake "confirmed
// key" (all messages except first message).
//
// When receiving a message from the peer, the node will create a new ecdh key pair and perform the key
// calculation for the proposed key. The peer will store the public key for the confirmation as pending to be
// confirmed in the next cycle. Also, if the message contains a confirmation (all but the very first message do),
// the node will use the stored private key to perform the ecdh key calculation and emit that key to be used in
// the crypto stream.
//
// Upon each cycle, a node first checks if it still has a proposed key that has not been confirmed by the remote
// peer. If so, a message must have been lost and the whole last message including the proposed key as well as the
// last confirmed key is being resent. If no proposed key is stored, the node will create a new ecdh key pair, and
// store the private key as proposed key. It then sends out a message containing the public key as proposal, as
// well as confirming the pending key. This key is also emitted to be added to the crypto stream but not to be
// used for encrypting.
//
// Monotonically increasing message ids guard the communication from message duplication and also serve as
// identifiers for the keys to be used in the crypto stream. Since the keys are rotating, the last 2 bits of the
// id are enough to identify the key.
//
// The whole communication is sent via the crypto stream and is therefore encrypted and protected against tampering.
use super::Key;
use crate::{error::Error, util::MsgBuffer};
use byteorder::{NetworkEndian, ReadBytesExt, WriteBytesExt};
use ring::{
agreement::{agree_ephemeral, EphemeralPrivateKey, UnparsedPublicKey, X25519},
rand::SystemRandom
rand::SystemRandom,
};
use smallvec::{smallvec, SmallVec};
use std::io::{self, Cursor, Read, Write};
type EcdhPublicKey = UnparsedPublicKey<SmallVec<[u8; 96]>>;
type EcdhPrivateKey = EphemeralPrivateKey;
pub struct RotationMessage {
message_id: u64,
propose: EcdhPublicKey,
confirm: Option<EcdhPublicKey>
confirm: Option<EcdhPublicKey>,
}
impl RotationMessage {
@ -86,13 +89,13 @@ pub struct RotationState {
pending: Option<(Key, EcdhPublicKey)>, // sent by remote, to be confirmed
proposed: Option<EcdhPrivateKey>, // my own, proposed but not confirmed
message_id: u64,
timeout: bool
timeout: bool,
}
pub struct RotatedKey {
pub key: Key,
pub id: u64,
pub use_for_sending: bool
pub use_for_sending: bool,
}
impl RotationState {
@ -134,10 +137,10 @@ impl RotationState {
}
fn derive_key(private_key: EcdhPrivateKey, public_key: EcdhPublicKey) -> Key {
agree_ephemeral(private_key, &public_key, (), |k| {
agree_ephemeral(private_key, &public_key, |k| {
let mut vec = Key::new();
vec.extend_from_slice(k);
Ok(vec)
vec
})
.unwrap()
}
@ -150,7 +153,7 @@ impl RotationState {
pub fn process_message(&mut self, msg: RotationMessage) -> Option<RotatedKey> {
if msg.message_id <= self.message_id {
return None
return None;
}
debug!("Received rotation message with id {}", msg.message_id);
self.timeout = false;
@ -162,7 +165,7 @@ impl RotationState {
if let Some(peer_key) = msg.confirm {
if let Some(private_key) = self.proposed.take() {
let key = Self::derive_key(private_key, peer_key);
return Some(RotatedKey { key, id: msg.message_id, use_for_sending: true })
return Some(RotatedKey { key, id: msg.message_id, use_for_sending: true });
}
}
None
@ -173,12 +176,12 @@ impl RotationState {
if let Some(ref private_key) = self.proposed {
// Still a proposed key that has not been confirmed, proposal must have been lost
if self.timeout {
let proposed_key = Self::compute_public_key(&private_key);
let proposed_key = Self::compute_public_key(private_key);
if let Some((ref confirmed_key, message_id)) = self.confirmed {
// Reconfirm last confirmed key
Self::send(
&RotationMessage { confirm: Some(confirmed_key.clone()), propose: proposed_key, message_id },
out
out,
);
} else {
// First message has been lost
@ -197,7 +200,7 @@ impl RotationState {
self.proposed = Some(private_key);
self.confirmed = Some((confirm_key.clone(), message_id));
Self::send(&RotationMessage { confirm: Some(confirm_key), propose: propose_key, message_id }, out);
return Some(RotatedKey { key, id: message_id, use_for_sending: false })
return Some(RotatedKey { key, id: message_id, use_for_sending: false });
} else {
// Nothing pending nor proposed, still waiting to receive message 1
// Do nothing, peer will retry
@ -216,7 +219,7 @@ mod tests {
impl MsgBuffer {
fn msg(&mut self) -> Option<RotationMessage> {
if self.is_empty() {
return None
return None;
}
let msg = RotationMessage::read_from(Cursor::new(self.message())).unwrap();
self.set_length(0);
@ -268,7 +271,7 @@ mod tests {
assert!(key2.is_some());
let key2 = key2.unwrap();
assert_eq!(key2.id, 2);
assert_eq!(key2.use_for_sending, false);
assert!(!key2.use_for_sending);
assert!(!out2.is_empty());
let msg2 = out2.msg().unwrap();
assert_eq!(msg2.message_id, 2);
@ -278,14 +281,14 @@ mod tests {
assert!(key.is_some());
let key = key.unwrap();
assert_eq!(key.id, 2);
assert_eq!(key.use_for_sending, true);
assert!(key.use_for_sending);
// Cycle 2
let key1 = node1.cycle(&mut out1);
let key2 = node2.cycle(&mut out2);
assert!(key1.is_some());
let key1 = key1.unwrap();
assert_eq!(key1.id, 3);
assert_eq!(key1.use_for_sending, false);
assert!(!key1.use_for_sending);
assert!(!out1.is_empty());
let msg1 = out1.msg().unwrap();
assert_eq!(msg1.message_id, 3);
@ -297,7 +300,7 @@ mod tests {
assert!(key.is_some());
let key = key.unwrap();
assert_eq!(key.id, 3);
assert_eq!(key.use_for_sending, true);
assert!(key.use_for_sending);
// Cycle 3
let key1 = node1.cycle(&mut out1);
let key2 = node2.cycle(&mut out2);
@ -306,7 +309,7 @@ mod tests {
assert!(key2.is_some());
let key2 = key2.unwrap();
assert_eq!(key2.id, 4);
assert_eq!(key2.use_for_sending, false);
assert!(!key2.use_for_sending);
assert!(!out2.is_empty());
let msg2 = out2.msg().unwrap();
assert_eq!(msg2.message_id, 4);
@ -316,7 +319,7 @@ mod tests {
assert!(key.is_some());
let key = key.unwrap();
assert_eq!(key.id, 4);
assert_eq!(key.use_for_sending, true);
assert!(key.use_for_sending);
}
#[test]

View File

@ -1,16 +1,16 @@
// 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::{
cmp,
collections::VecDeque,
convert::TryInto,
fmt,
fs::{self, File},
io::{self, BufRead, BufReader, Cursor, Error as IoError, Read, Write},
net::{Ipv4Addr, UdpSocket},
os::unix::io::{AsRawFd, RawFd},
convert::TryInto,
os::{unix::io::AsRawFd, fd::RawFd},
str,
str::FromStr
};
@ -19,30 +19,36 @@ use crate::{crypto, error::Error, util::MsgBuffer};
static TUNSETIFF: libc::c_ulong = 1074025674;
#[repr(C)]
#[derive(Copy, Clone)]
struct IfReqDataAddr {
af: libc::c_int,
addr: Ipv4Addr
}
#[repr(C)]
union IfReqData {
flags: libc::c_short,
value: libc::c_int,
addr: (libc::c_short, Ipv4Addr),
_dummy: [u8; 24]
addr: IfReqDataAddr,
_dummy: [u8; 24],
}
#[repr(C)]
struct IfReq {
ifr_name: [u8; libc::IF_NAMESIZE],
data: IfReqData
data: IfReqData,
}
impl IfReq {
fn new(name: &str) -> Self {
assert!(name.len() < libc::IF_NAMESIZE);
let mut ifr_name = [0 as u8; libc::IF_NAMESIZE];
let mut ifr_name = [0; libc::IF_NAMESIZE];
ifr_name[..name.len()].clone_from_slice(name.as_bytes());
Self { ifr_name, data: IfReqData { _dummy: [0; 24] } }
}
}
/// The type of a tun/tap device
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
pub enum Type {
@ -52,9 +58,6 @@ pub enum Type {
/// Tap interface: This interface transports Ethernet frames.
#[serde(rename = "tap")]
Tap,
/// Dummy interface: This interface does nothing.
#[serde(rename = "dummy")]
Dummy
}
impl fmt::Display for Type {
@ -62,7 +65,6 @@ impl fmt::Display for Type {
match *self {
Type::Tun => write!(formatter, "tun"),
Type::Tap => write!(formatter, "tap"),
Type::Dummy => write!(formatter, "dummy")
}
}
}
@ -74,8 +76,7 @@ impl FromStr for Type {
Ok(match &text.to_lowercase() as &str {
"tun" => Self::Tun,
"tap" => Self::Tap,
"dummy" => Self::Dummy,
_ => return Err("Unknown device type")
_ => return Err("Unknown device type"),
})
}
}
@ -114,15 +115,13 @@ pub trait Device: AsRawFd {
fn get_ip(&self) -> Result<Ipv4Addr, Error>;
}
/// Represents a tun/tap device
pub struct TunTapDevice {
fd: File,
ifname: String,
type_: Type
type_: Type,
}
impl TunTapDevice {
/// Creates a new tun/tap device
///
@ -144,14 +143,10 @@ impl TunTapDevice {
#[allow(clippy::useless_conversion)]
pub fn new(ifname: &str, type_: Type, path: Option<&str>) -> io::Result<Self> {
let path = path.unwrap_or_else(|| Self::default_path(type_));
if type_ == Type::Dummy {
return Self::dummy(ifname, path, type_)
}
let fd = fs::OpenOptions::new().read(true).write(true).open(path)?;
let flags = match type_ {
Type::Tun => libc::IFF_TUN | libc::IFF_NO_PI,
Type::Tap => libc::IFF_TAP | libc::IFF_NO_PI,
Type::Dummy => unreachable!()
};
let mut ifreq = IfReq::new(ifname);
ifreq.data.flags = flags as libc::c_short;
@ -164,7 +159,7 @@ impl TunTapDevice {
ifname = ifname.trim_end_matches('\0').to_owned();
Ok(Self { fd, ifname, type_ })
}
_ => Err(IoError::last_os_error())
_ => Err(IoError::last_os_error()),
}
}
@ -173,32 +168,9 @@ impl TunTapDevice {
pub fn default_path(type_: Type) -> &'static str {
match type_ {
Type::Tun | Type::Tap => "/dev/net/tun",
Type::Dummy => "/dev/null"
}
}
/// Creates a dummy device based on an existing file
///
/// This method opens a regular or special file and reads from it to receive packets and
/// writes to it to send packets. This method does not use a networking device and therefore
/// can be used for testing.
///
/// The parameter `path` is the file that should be used. Special files like `/dev/null`,
/// named pipes and unix sockets can be used with this method.
///
/// Both `ifname` and `type_` parameters have no effect.
///
/// # Errors
/// This method will return an error if the file can not be opened for reading and writing.
#[allow(dead_code)]
pub fn dummy(ifname: &str, path: &str, type_: Type) -> io::Result<Self> {
Ok(TunTapDevice {
fd: fs::OpenOptions::new().create(true).read(true).write(true).open(path)?,
ifname: ifname.to_string(),
type_
})
}
#[cfg(any(target_os = "linux", target_os = "android"))]
#[inline]
fn correct_data_after_read(&mut self, _buffer: &mut MsgBuffer) {}
@ -243,7 +215,7 @@ impl TunTapDevice {
// IP version
4 => buffer.message_mut()[0..4].copy_from_slice(&[0x00, 0x00, 0x08, 0x00]),
6 => buffer.message_mut()[0..4].copy_from_slice(&[0x00, 0x00, 0x86, 0xdd]),
_ => unreachable!()
_ => unreachable!(),
}
}
}
@ -255,7 +227,7 @@ impl TunTapDevice {
+ 1 /* message type header */
+ match self.type_ {
Type::Tap => 14, /* inner ethernet header */
Type::Tun | Type::Dummy => 0
Type::Tun => 0
}
}
@ -315,7 +287,7 @@ impl Device for TunTapDevice {
self.correct_data_before_write(buffer);
match self.fd.write_all(buffer.message()) {
Ok(_) => self.fd.flush().map_err(|e| Error::DeviceIo("Flush error", e)),
Err(e) => Err(Error::DeviceIo("Write error", e))
Err(e) => Err(Error::DeviceIo("Write error", e)),
}
}
@ -331,10 +303,9 @@ impl AsRawFd for TunTapDevice {
}
}
pub struct MockDevice {
inbound: VecDeque<Vec<u8>>,
outbound: VecDeque<Vec<u8>>
outbound: VecDeque<Vec<u8>>,
}
impl MockDevice {
@ -357,11 +328,11 @@ impl MockDevice {
impl Device for MockDevice {
fn get_type(&self) -> Type {
Type::Dummy
Type::Tun
}
fn ifname(&self) -> &str {
unimplemented!()
"mock0"
}
fn read(&mut self, buffer: &mut MsgBuffer) -> Result<(), Error> {
@ -376,7 +347,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(())
}
@ -387,7 +358,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) }
}
}
@ -398,7 +369,6 @@ impl AsRawFd for MockDevice {
}
}
#[allow(clippy::useless_conversion)]
fn set_device_mtu(ifname: &str, mtu: usize) -> io::Result<()> {
let sock = UdpSocket::bind("0.0.0.0:0")?;
@ -407,7 +377,7 @@ fn set_device_mtu(ifname: &str, mtu: usize) -> io::Result<()> {
let res = unsafe { libc::ioctl(sock.as_raw_fd(), libc::SIOCSIFMTU.try_into().unwrap(), &mut ifreq) };
match res {
0 => Ok(()),
_ => Err(IoError::last_os_error())
_ => Err(IoError::last_os_error()),
}
}
@ -418,7 +388,7 @@ fn get_device_mtu(ifname: &str) -> io::Result<usize> {
let res = unsafe { libc::ioctl(sock.as_raw_fd(), libc::SIOCGIFMTU.try_into().unwrap(), &mut ifreq) };
match res {
0 => Ok(unsafe { ifreq.data.value as usize }),
_ => Err(IoError::last_os_error())
_ => Err(IoError::last_os_error()),
}
}
@ -429,14 +399,14 @@ fn get_device_addr(ifname: &str) -> io::Result<Ipv4Addr> {
let res = unsafe { libc::ioctl(sock.as_raw_fd(), libc::SIOCGIFADDR.try_into().unwrap(), &mut ifreq) };
match res {
0 => {
let af = unsafe { ifreq.data.addr.0 };
let af = unsafe { ifreq.data.addr.af };
if af as libc::c_int != libc::AF_INET {
return Err(io::Error::new(io::ErrorKind::AddrNotAvailable, "Invalid address family".to_owned()))
return Err(io::Error::new(io::ErrorKind::AddrNotAvailable, "Invalid address family".to_owned()));
}
let ip = unsafe { ifreq.data.addr.1 };
let ip = unsafe { ifreq.data.addr.addr };
Ok(ip)
}
_ => Err(IoError::last_os_error())
_ => Err(IoError::last_os_error()),
}
}
@ -444,11 +414,12 @@ fn get_device_addr(ifname: &str) -> io::Result<Ipv4Addr> {
fn set_device_addr(ifname: &str, addr: Ipv4Addr) -> io::Result<()> {
let sock = UdpSocket::bind("0.0.0.0:0")?;
let mut ifreq = IfReq::new(ifname);
ifreq.data.addr = (libc::AF_INET as libc::c_short, addr);
ifreq.data.addr.af = libc::AF_INET as libc::c_int;
ifreq.data.addr.addr = addr;
let res = unsafe { libc::ioctl(sock.as_raw_fd(), libc::SIOCSIFADDR.try_into().unwrap(), &mut ifreq) };
match res {
0 => Ok(()),
_ => Err(IoError::last_os_error())
_ => Err(IoError::last_os_error()),
}
}
@ -460,14 +431,14 @@ fn get_device_netmask(ifname: &str) -> io::Result<Ipv4Addr> {
let res = unsafe { libc::ioctl(sock.as_raw_fd(), libc::SIOCGIFNETMASK.try_into().unwrap(), &mut ifreq) };
match res {
0 => {
let af = unsafe { ifreq.data.addr.0 };
let af = unsafe { ifreq.data.addr.af };
if af as libc::c_int != libc::AF_INET {
return Err(io::Error::new(io::ErrorKind::AddrNotAvailable, "Invalid address family".to_owned()))
return Err(io::Error::new(io::ErrorKind::AddrNotAvailable, "Invalid address family".to_owned()));
}
let ip = unsafe { ifreq.data.addr.1 };
let ip = unsafe { ifreq.data.addr.addr };
Ok(ip)
}
_ => Err(IoError::last_os_error())
_ => Err(IoError::last_os_error()),
}
}
@ -475,11 +446,12 @@ fn get_device_netmask(ifname: &str) -> io::Result<Ipv4Addr> {
fn set_device_netmask(ifname: &str, addr: Ipv4Addr) -> io::Result<()> {
let sock = UdpSocket::bind("0.0.0.0:0")?;
let mut ifreq = IfReq::new(ifname);
ifreq.data.addr = (libc::AF_INET as libc::c_short, addr);
ifreq.data.addr.af = libc::AF_INET as libc::c_int;
ifreq.data.addr.addr = addr;
let res = unsafe { libc::ioctl(sock.as_raw_fd(), libc::SIOCSIFNETMASK.try_into().unwrap(), &mut ifreq) };
match res {
0 => Ok(()),
_ => Err(IoError::last_os_error())
_ => Err(IoError::last_os_error()),
}
}
@ -488,7 +460,7 @@ fn set_device_enabled(ifname: &str, up: bool) -> io::Result<()> {
let sock = UdpSocket::bind("0.0.0.0:0")?;
let mut ifreq = IfReq::new(ifname);
if unsafe { libc::ioctl(sock.as_raw_fd(), libc::SIOCGIFFLAGS.try_into().unwrap(), &mut ifreq) } != 0 {
return Err(IoError::last_os_error())
return Err(IoError::last_os_error());
}
if up {
unsafe { ifreq.data.value |= libc::IFF_UP | libc::IFF_RUNNING }
@ -498,11 +470,10 @@ fn set_device_enabled(ifname: &str, up: bool) -> io::Result<()> {
let res = unsafe { libc::ioctl(sock.as_raw_fd(), libc::SIOCSIFFLAGS.try_into().unwrap(), &mut ifreq) };
match res {
0 => Ok(()),
_ => Err(IoError::last_os_error())
_ => Err(IoError::last_os_error()),
}
}
fn get_default_device() -> io::Result<String> {
let fd = BufReader::new(File::open("/proc/net/route")?);
let mut best = None;
@ -511,7 +482,7 @@ fn get_default_device() -> io::Result<String> {
let parts = line.split('\t').collect::<Vec<_>>();
if parts[1] == "00000000" {
best = Some(parts[0].to_string());
break
break;
}
if parts[2] != "00000000" {
best = Some(parts[0].to_string())

View File

@ -1,8 +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)
use thiserror::Error;
use std::io;
#[derive(Error, Debug)]
pub enum Error {
/// Crypto init error, this is recoverable
@ -48,5 +51,5 @@ pub enum Error {
Parse(&'static str),
#[error("Name can not be resolved: {0}")]
NameUnresolvable(String)
NameUnresolvable(String),
}

64
src/installer.rs Normal file
View File

@ -0,0 +1,64 @@
use crate::{error::Error, util::run_cmd};
use std::{
env,
fs::{self, File},
io::Write,
os::unix::fs::PermissionsExt,
process::Command,
};
const MANPAGE: &[u8] = include_bytes!("../target/vpncloud.1.gz");
const SERVICE_FILE: &[u8] = include_bytes!("../assets/vpncloud@.service");
const TARGET_FILE: &[u8] = include_bytes!("../assets/vpncloud.target");
const WS_PROXY_SERVICE_FILE: &[u8] = include_bytes!("../assets/vpncloud-wsproxy.service");
const EXAMPLE_CONFIG: &[u8] = include_bytes!("../assets/example.net.disabled");
fn systemctl_daemon_reload() {
let mut cmd = Command::new("systemctl");
cmd.arg("daemon-reload");
run_cmd(cmd);
}
pub fn install() -> Result<(), Error> {
env::current_exe()
.and_then(|p| fs::copy(p, "/usr/bin/vpncloud"))
.map_err(|e| Error::FileIo("Failed to copy binary", e))?;
fs::set_permissions("/usr/bin/vpncloud", fs::Permissions::from_mode(0o755))
.map_err(|e| Error::FileIo("Failed to set permissions for binary", e))?;
fs::create_dir_all("/etc/vpncloud").map_err(|e| Error::FileIo("Failed to create config folder", e))?;
fs::set_permissions("/etc/vpncloud", fs::Permissions::from_mode(0o700))
.map_err(|e| Error::FileIo("Failed to set permissions for config folder", e))?;
File::create("/etc/vpncloud/example.net.disabled")
.and_then(|mut f| f.write_all(EXAMPLE_CONFIG))
.map_err(|e| Error::FileIo("Failed to create example config", e))?;
File::create("/usr/share/man/man1/vpncloud.1.gz")
.and_then(|mut f| f.write_all(MANPAGE))
.map_err(|e| Error::FileIo("Failed to create manpage", e))?;
File::create("/lib/systemd/system/vpncloud@.service")
.and_then(|mut f| f.write_all(SERVICE_FILE))
.map_err(|e| Error::FileIo("Failed to create service file", e))?;
File::create("/lib/systemd/system/vpncloud.target")
.and_then(|mut f| f.write_all(TARGET_FILE))
.map_err(|e| Error::FileIo("Failed to create service target file", e))?;
File::create("/lib/systemd/system/vpncloud-wsproxy.service")
.and_then(|mut f| f.write_all(WS_PROXY_SERVICE_FILE))
.map_err(|e| Error::FileIo("Failed to create wsporxy service file", e))?;
systemctl_daemon_reload();
info!("Install successful");
Ok(())
}
pub fn uninstall() -> Result<(), Error> {
fs::remove_file("/etc/vpncloud/example.net.disabled").map_err(|e| Error::FileIo("Failed to remove binary", e))?;
fs::remove_file("/usr/share/man/man1/vpncloud.1.gz").map_err(|e| Error::FileIo("Failed to remove manpage", e))?;
fs::remove_file("/lib/systemd/system/vpncloud@.service")
.map_err(|e| Error::FileIo("Failed to remove service file", e))?;
fs::remove_file("/lib/systemd/system/vpncloud.target")
.map_err(|e| Error::FileIo("Failed to remove service target file", e))?;
fs::remove_file("/lib/systemd/system/vpncloud-wsproxy.service")
.map_err(|e| Error::FileIo("Failed to remove wsproxy service file", e))?;
fs::remove_file("/usr/bin/vpncloud").map_err(|e| Error::FileIo("Failed to remove binary", e))?;
systemctl_daemon_reload();
info!("Uninstall successful");
Ok(())
}

View File

@ -1,14 +1,14 @@
// 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_attr(feature = "bench", feature(test))]
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde;
#[macro_use] extern crate log;
#[macro_use] extern crate serde_derive;
#[cfg(test)] extern crate tempfile;
#[cfg(feature = "bench")] extern crate test;
#[cfg(test)]
extern crate tempfile;
#[macro_use]
pub mod util;
@ -21,6 +21,8 @@ pub mod config;
pub mod crypto;
pub mod device;
pub mod error;
#[cfg(feature = "installer")]
pub mod installer;
pub mod messages;
pub mod net;
pub mod oldconfig;
@ -30,6 +32,10 @@ pub mod port_forwarding;
pub mod table;
pub mod traffic;
pub mod types;
#[cfg(feature = "wizard")]
pub mod wizard;
#[cfg(feature = "websocket")]
pub mod wsproxy;
use structopt::StructOpt;
@ -39,26 +45,27 @@ use std::{
net::{Ipv4Addr, UdpSocket},
os::unix::fs::PermissionsExt,
path::Path,
process::Command,
process,
str::FromStr,
sync::Mutex,
thread
};
use crate::{
cloud::GenericCloud,
config::{Args, Config},
config::{Args, Command, Config, DEFAULT_PORT},
crypto::Crypto,
device::{Device, TunTapDevice, Type},
net::Socket,
oldconfig::OldConfigFile,
payload::Protocol,
port_forwarding::PortForwarding,
util::SystemTimeSource
util::SystemTimeSource,
};
#[cfg(feature = "websocket")]
use crate::wsproxy::ProxyConnection;
struct DualLogger {
file: Option<Mutex<File>>
file: Option<Mutex<File>>,
}
impl DualLogger {
@ -88,7 +95,7 @@ impl log::Log for DualLogger {
println!("{} - {}", record.level(), record.args());
if let Some(ref file) = self.file {
let mut file = file.lock().expect("Lock poisoned");
let time = time::OffsetDateTime::now_local().format("%F %H:%M:%S");
let time = chrono::Local::now().format("%F %H:%M:%S");
writeln!(file, "{} - {} - {}", time, record.level(), record.args())
.expect("Failed to write to logfile");
}
@ -105,8 +112,8 @@ impl log::Log for DualLogger {
}
fn run_script(script: &str, ifname: &str) {
let mut cmd = Command::new("sh");
cmd.arg("-c").arg(&script).env("IFNAME", ifname);
let mut cmd = process::Command::new("sh");
cmd.arg("-c").arg(script).env("IFNAME", ifname);
debug!("Running script: {:?}", cmd);
match cmd.status() {
Ok(status) => {
@ -114,18 +121,18 @@ fn run_script(script: &str, ifname: &str) {
error!("Script returned with error: {:?}", status.code())
}
}
Err(e) => error!("Failed to execute script {:?}: {}", script, e)
Err(e) => error!("Failed to execute script {:?}: {}", script, e),
}
}
fn parse_ip_netmask(addr: &str) -> Result<(Ipv4Addr, Ipv4Addr), String> {
let (ip_str, len_str) = match addr.find('/') {
Some(pos) => (&addr[..pos], &addr[pos + 1..]),
None => (addr, "24")
None => (addr, "24"),
};
let prefix_len = u8::from_str(len_str).map_err(|_| format!("Invalid prefix length: {}", len_str))?;
if prefix_len > 32 {
return Err(format!("Invalid prefix length: {}", prefix_len))
return Err(format!("Invalid prefix length: {}", prefix_len));
}
let ip = Ipv4Addr::from_str(ip_str).map_err(|_| format!("Invalid ip address: {}", ip_str))?;
let netmask = Ipv4Addr::from(u32::max_value().checked_shl(32 - prefix_len as u32).unwrap());
@ -140,6 +147,7 @@ fn setup_device(config: &Config) -> TunTapDevice {
config.device_name
);
info!("Opened device {}", device.ifname());
config.call_hook("device_setup", vec![("IFNAME", device.ifname())], true);
if let Err(err) = device.set_mtu(None) {
error!("Error setting optimal MTU on {}: {}", device.ifname(), err);
}
@ -159,14 +167,14 @@ fn setup_device(config: &Config) -> TunTapDevice {
warn!("Your networking configuration might be affected by a vulnerability (https://vpncloud.ddswd.de/docs/security/cve-2019-14899/), please change your rp_filter setting to 1 (currently {}).", val);
}
}
config.call_hook("device_configured", vec![("IFNAME", device.ifname())], true);
device
}
#[allow(clippy::cognitive_complexity)]
fn run<P: Protocol>(config: Config) {
fn run<P: Protocol, S: Socket>(config: Config, socket: S) {
let device = setup_device(&config);
let port_forwarding = if config.port_forwarding { PortForwarding::new(config.listen.port()) } else { None };
let port_forwarding = if config.port_forwarding { socket.create_port_forwarding() } else { None };
let stats_file = match config.stats_file {
None => None,
Some(ref name) => {
@ -183,8 +191,12 @@ fn run<P: Protocol>(config: Config) {
}
};
let mut cloud =
GenericCloud::<TunTapDevice, P, UdpSocket, SystemTimeSource>::new(&config, device, port_forwarding, stats_file);
for addr in config.peers {
GenericCloud::<TunTapDevice, P, S, SystemTimeSource>::new(&config, socket, device, port_forwarding, stats_file);
for mut addr in config.peers {
if addr.find(':').unwrap_or(0) <= addr.find(']').unwrap_or(0) {
// : not present or only in IPv6 address
addr = format!("{}:{}", addr, DEFAULT_PORT)
}
try_fail!(cloud.connect(&addr as &str), "Failed to send message to {}: {}", &addr);
cloud.add_reconnect_peer(addr);
}
@ -199,8 +211,6 @@ fn run<P: Protocol>(config: Config) {
}
if let Some(pid_file) = config.pid_file {
daemonize = daemonize.pid_file(pid_file).chown_pid_file(true);
// Give child process some time to write PID file
daemonize = daemonize.exit_action(|| thread::sleep(std::time::Duration::from_millis(10)));
}
try_fail!(daemonize.start(), "Failed to daemonize: {}");
} else if config.user.is_some() || config.group.is_some() {
@ -224,15 +234,7 @@ fn main() {
let args: Args = Args::from_args();
if args.version {
println!("VpnCloud v{}", env!("CARGO_PKG_VERSION"));
return
}
if args.genkey {
let (privkey, pubkey) = Crypto::generate_keypair(args.password.as_deref());
println!("Private key: {}\nPublic key: {}\n", privkey, pubkey);
println!(
"Attention: Keep the private key secret and use only the public key on other nodes to establish trust."
);
return
return;
}
let logger = try_fail!(DualLogger::new(args.log_file.as_ref()), "Failed to open logfile: {}");
log::set_boxed_logger(Box::new(logger)).unwrap();
@ -244,24 +246,56 @@ fn main() {
} else {
log::LevelFilter::Info
});
if args.migrate_config {
let file = args.config.unwrap();
info!("Trying to convert from old config format");
let f = try_fail!(File::open(&file), "Failed to open config file: {:?}");
let config_file_old: OldConfigFile =
try_fail!(serde_yaml::from_reader(f), "Config file not valid for version 1: {:?}");
let new_config = config_file_old.convert();
info!("Successfully converted from old format");
info!("Renaming original file to {}.orig", file);
try_fail!(fs::rename(&file, format!("{}.orig", file)), "Failed to rename original file: {:?}");
info!("Writing new config back into {}", file);
let f = try_fail!(File::create(&file), "Failed to open config file: {:?}");
try_fail!(
fs::set_permissions(&file, fs::Permissions::from_mode(0o600)),
"Failed to set permissions on file: {:?}"
);
try_fail!(serde_yaml::to_writer(f, &new_config), "Failed to write converted config: {:?}");
return
if let Some(cmd) = args.cmd {
match cmd {
Command::GenKey { password } => {
let (privkey, pubkey) = Crypto::generate_keypair(password.as_deref());
println!("Private key: {}\nPublic key: {}\n", privkey, pubkey);
println!(
"Attention: Keep the private key secret and use only the public key on other nodes to establish trust."
);
}
Command::MigrateConfig { config_file } => {
info!("Trying to convert from old config format");
let f = try_fail!(File::open(&config_file), "Failed to open config file: {:?}");
let config_file_old: OldConfigFile =
try_fail!(serde_yaml::from_reader(f), "Config file not valid for version 1: {:?}");
let new_config = config_file_old.convert();
info!("Successfully converted from old format");
info!("Renaming original file to {}.orig", config_file);
try_fail!(
fs::rename(&config_file, format!("{}.orig", config_file)),
"Failed to rename original file: {:?}"
);
info!("Writing new config back into {}", config_file);
let f = try_fail!(File::create(&config_file), "Failed to open config file: {:?}");
try_fail!(
fs::set_permissions(&config_file, fs::Permissions::from_mode(0o600)),
"Failed to set permissions on file: {:?}"
);
try_fail!(serde_yaml::to_writer(f, &new_config), "Failed to write converted config: {:?}");
}
Command::Completion { shell } => {
Args::clap().gen_completions_to(env!("CARGO_PKG_NAME"), shell, &mut io::stdout());
}
#[cfg(feature = "websocket")]
Command::WsProxy { listen } => {
try_fail!(wsproxy::run_proxy(&listen), "Failed to run websocket proxy: {:?}");
}
#[cfg(feature = "wizard")]
Command::Config { name } => {
try_fail!(wizard::configure(name), "Wizard failed: {}");
}
#[cfg(feature = "installer")]
Command::Install { uninstall } => {
if uninstall {
try_fail!(installer::uninstall(), "Uninstall failed: {}");
} else {
try_fail!(installer::install(), "Install failed: {}");
}
}
}
return;
}
let mut config = Config::default();
if let Some(ref file) = args.config {
@ -284,9 +318,22 @@ fn main() {
}
config.merge_args(args);
debug!("Config: {:?}", config);
if config.crypto.password.is_none() && config.crypto.private_key.is_none() {
error!("Either password or private key must be set in config or given as parameter");
return;
}
#[cfg(feature = "websocket")]
if config.listen.starts_with("ws://") {
let socket = try_fail!(ProxyConnection::listen(&config.listen), "Failed to open socket {}: {}", config.listen);
match config.device_type {
Type::Tap => run::<payload::Frame, _>(config, socket),
Type::Tun => run::<payload::Packet, _>(config, socket),
}
return;
}
let socket = try_fail!(UdpSocket::listen(&config.listen), "Failed to open socket {}: {}", config.listen);
match config.device_type {
Type::Tap => run::<payload::Frame>(config),
Type::Tun => run::<payload::Packet>(config),
Type::Dummy => run::<payload::Frame>(config)
Type::Tap => run::<payload::Frame, _>(config, socket),
Type::Tun => run::<payload::Packet, _>(config, socket),
}
}

View File

@ -1,34 +1,32 @@
// 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::{
crypto::Payload,
error::Error,
types::{NodeId, Range, RangeList, NODE_ID_BYTES},
util::MsgBuffer
util::MsgBuffer,
};
use byteorder::{NetworkEndian, ReadBytesExt, WriteBytesExt};
use smallvec::{smallvec, SmallVec};
use std::{
io::{self, Cursor, Read, Seek, SeekFrom, Take, Write},
net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6}
net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6},
};
pub const MESSAGE_TYPE_DATA: u8 = 0;
pub const MESSAGE_TYPE_NODE_INFO: u8 = 1;
pub const MESSAGE_TYPE_KEEPALIVE: u8 = 2;
pub const MESSAGE_TYPE_CLOSE: u8 = 0xff;
pub type AddrList = SmallVec<[SocketAddr; 4]>;
pub type PeerList = SmallVec<[PeerInfo; 16]>;
#[derive(Debug, PartialEq)]
pub struct PeerInfo {
pub node_id: Option<NodeId>,
pub addrs: AddrList
pub addrs: AddrList,
}
#[derive(Debug, PartialEq)]
@ -36,7 +34,8 @@ pub struct NodeInfo {
pub node_id: NodeId,
pub peers: PeerList,
pub claims: RangeList,
pub peer_timeout: Option<u16>
pub peer_timeout: Option<u16>,
pub addrs: AddrList,
}
impl NodeInfo {
@ -45,35 +44,46 @@ impl NodeInfo {
const PART_NODEID: u8 = 4;
const PART_PEERS: u8 = 1;
const PART_PEER_TIMEOUT: u8 = 3;
const PART_ADDRS: u8 = 5;
fn read_addr_list<R: Read>(r: &mut Take<R>) -> Result<AddrList, io::Error> {
let flags = r.read_u8()?;
Self::read_addr_list_inner(r, flags)
}
fn read_addr_list_inner<R: Read>(r: &mut Take<R>, flags: u8) -> Result<AddrList, io::Error> {
let num_ipv4_addrs = (flags & 0x07) as usize;
let num_ipv6_addrs = (flags & 0x38) as usize / 8;
let mut addrs = SmallVec::with_capacity(num_ipv4_addrs + num_ipv6_addrs);
for _ in 0..num_ipv6_addrs {
let mut ip = [0u8; 16];
r.read_exact(&mut ip)?;
let port = r.read_u16::<NetworkEndian>()?;
let addr = SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::from(ip), port, 0, 0));
addrs.push(addr);
}
for _ in 0..num_ipv4_addrs {
let mut ip = [0u8; 4];
r.read_exact(&mut ip)?;
let port = r.read_u16::<NetworkEndian>()?;
let addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::from(ip), port));
addrs.push(addr);
}
Ok(addrs)
}
fn decode_peer_list_part<R: Read>(r: &mut Take<R>) -> Result<PeerList, io::Error> {
let mut peers = smallvec![];
while r.limit() > 0 {
let flags = r.read_u8()?;
let has_node_id = (flags & 0x80) != 0;
let num_ipv4_addrs = (flags & 0x07) as usize;
let num_ipv6_addrs = (flags & 0x38) as usize / 8;
let mut node_id = None;
if has_node_id {
let mut id = [0; NODE_ID_BYTES];
r.read_exact(&mut id)?;
node_id = Some(id)
}
let mut addrs = SmallVec::with_capacity(num_ipv4_addrs + num_ipv6_addrs);
for _ in 0..num_ipv6_addrs {
let mut ip = [0u8; 16];
r.read_exact(&mut ip)?;
let port = r.read_u16::<NetworkEndian>()?;
let addr = SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::from(ip), port, 0, 0));
addrs.push(addr);
}
for _ in 0..num_ipv4_addrs {
let mut ip = [0u8; 4];
r.read_exact(&mut ip)?;
let port = r.read_u16::<NetworkEndian>()?;
let addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::from(ip), port));
addrs.push(addr);
}
let addrs = Self::read_addr_list_inner(r, flags)?;
peers.push(PeerInfo { addrs, node_id })
}
Ok(peers)
@ -92,10 +102,11 @@ impl NodeInfo {
let mut claims = smallvec![];
let mut peer_timeout = None;
let mut node_id = None;
let mut addrs = smallvec![];
loop {
let part = r.read_u8().map_err(|_| Error::Message("Truncated message"))?;
if part == Self::PART_END {
break
break;
}
let part_len = r.read_u16::<NetworkEndian>().map_err(|_| Error::Message("Truncated message"))? as usize;
let mut rp = r.take(part_len as u64);
@ -113,6 +124,9 @@ impl NodeInfo {
rp.read_exact(&mut data).map_err(|_| Error::Message("Truncated message"))?;
node_id = Some(data);
}
Self::PART_ADDRS => {
addrs = Self::read_addr_list(&mut rp).map_err(|_| Error::Message("Truncated message"))?;
}
_ => {
let mut data = vec![0; part_len];
rp.read_exact(&mut data).map_err(|_| Error::Message("Truncated message"))?;
@ -122,9 +136,9 @@ impl NodeInfo {
}
let node_id = match node_id {
Some(node_id) => node_id,
None => return Err(Error::Message("Payload without node_id"))
None => return Err(Error::Message("Payload without node_id")),
};
Ok(Self { node_id, peers, claims, peer_timeout })
Ok(Self { node_id, peers, claims, peer_timeout, addrs })
}
pub fn decode<R: Read>(r: R) -> Result<Self, Error> {
@ -138,7 +152,7 @@ impl NodeInfo {
for a in &p.addrs {
match a {
SocketAddr::V4(addr) => addr_ipv4.push(*addr),
SocketAddr::V6(addr) => addr_ipv6.push(*addr)
SocketAddr::V6(addr) => addr_ipv6.push(*addr),
}
}
while addr_ipv4.len() >= 8 {
@ -167,8 +181,36 @@ impl NodeInfo {
Ok(())
}
fn encode_addrs_part<W: Write>(&self, mut out: W) -> Result<(), io::Error> {
let mut addr_ipv4: SmallVec<[SocketAddrV4; 16]> = smallvec![];
let mut addr_ipv6: SmallVec<[SocketAddrV6; 16]> = smallvec![];
for a in &self.addrs {
match a {
SocketAddr::V4(addr) => addr_ipv4.push(*addr),
SocketAddr::V6(addr) => addr_ipv6.push(*addr),
}
}
while addr_ipv4.len() >= 8 {
addr_ipv4.pop();
}
while addr_ipv6.len() >= 8 {
addr_ipv6.pop();
}
let flags = addr_ipv6.len() as u8 * 8 + addr_ipv4.len() as u8;
out.write_u8(flags)?;
for a in addr_ipv6 {
out.write_all(&a.ip().octets())?;
out.write_u16::<NetworkEndian>(a.port())?;
}
for a in addr_ipv4 {
out.write_all(&a.ip().octets())?;
out.write_u16::<NetworkEndian>(a.port())?;
}
Ok(())
}
fn encode_part<F: FnOnce(&mut Cursor<&mut [u8]>) -> Result<(), io::Error>>(
cursor: &mut Cursor<&mut [u8]>, part: u8, f: F
cursor: &mut Cursor<&mut [u8]>, part: u8, f: F,
) -> Result<(), io::Error> {
cursor.write_u8(part)?;
cursor.write_u16::<NetworkEndian>(0)?;
@ -199,6 +241,7 @@ impl NodeInfo {
cursor.write_u16::<NetworkEndian>(timeout)
})?
}
Self::encode_part(&mut cursor, Self::PART_ADDRS, |cursor| self.encode_addrs_part(cursor))?;
cursor.write_u8(Self::PART_END)?;
len = cursor.position() as usize;
}
@ -211,7 +254,6 @@ impl NodeInfo {
}
}
impl Payload for NodeInfo {
fn write_to(&self, buffer: &mut MsgBuffer) {
self.encode(buffer)

View File

@ -1,34 +1,57 @@
// 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::{
collections::{HashMap, VecDeque},
io::{self, ErrorKind},
net::{IpAddr, SocketAddr, UdpSocket},
net::{IpAddr, Ipv6Addr, SocketAddr, UdpSocket},
os::unix::io::{AsRawFd, RawFd},
sync::atomic::{AtomicBool, Ordering}
sync::atomic::{AtomicBool, Ordering},
};
use super::util::{MockTimeSource, MsgBuffer, Time, TimeSource};
use crate::{config::DEFAULT_PORT, port_forwarding::PortForwarding};
pub fn mapped_addr(addr: SocketAddr) -> SocketAddr {
// HOT PATH
match addr {
SocketAddr::V4(addr4) => SocketAddr::new(IpAddr::V6(addr4.ip().to_ipv6_mapped()), addr4.port()),
_ => addr
_ => addr,
}
}
pub fn get_ip() -> IpAddr {
let s = UdpSocket::bind("0.0.0.0:0").unwrap();
s.connect("8.8.8.8:0").unwrap();
s.local_addr().unwrap().ip()
}
pub trait Socket: AsRawFd + Sized {
fn listen(addr: SocketAddr) -> Result<Self, io::Error>;
fn listen(addr: &str) -> Result<Self, io::Error>;
fn receive(&mut self, buffer: &mut MsgBuffer) -> Result<SocketAddr, io::Error>;
fn send(&mut self, data: &[u8], addr: SocketAddr) -> Result<usize, io::Error>;
fn address(&self) -> Result<SocketAddr, io::Error>;
fn create_port_forwarding(&self) -> Option<PortForwarding>;
}
pub fn parse_listen(addr: &str, default_port: u16) -> SocketAddr {
if let Some(addr) = addr.strip_prefix("*:") {
let port = try_fail!(addr.parse::<u16>(), "Invalid port: {}");
SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), port)
} else if addr.contains(':') {
try_fail!(addr.parse::<SocketAddr>(), "Invalid address: {}: {}", addr)
} else if let Ok(port) = addr.parse::<u16>() {
SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), port)
} else {
let ip = try_fail!(addr.parse::<IpAddr>(), "Invalid addr: {}");
SocketAddr::new(ip, default_port)
}
}
impl Socket for UdpSocket {
fn listen(addr: SocketAddr) -> Result<Self, io::Error> {
fn listen(addr: &str) -> Result<Self, io::Error> {
let addr = mapped_addr(parse_listen(addr, DEFAULT_PORT));
UdpSocket::bind(addr)
}
@ -44,7 +67,13 @@ impl Socket for UdpSocket {
}
fn address(&self) -> Result<SocketAddr, io::Error> {
self.local_addr()
let mut addr = self.local_addr()?;
addr.set_ip(get_ip());
Ok(addr)
}
fn create_port_forwarding(&self) -> Option<PortForwarding> {
PortForwarding::new(self.address().unwrap().port())
}
}
@ -57,7 +86,7 @@ pub struct MockSocket {
nat_peers: HashMap<SocketAddr, Time>,
address: SocketAddr,
outbound: VecDeque<(SocketAddr, Vec<u8>)>,
inbound: VecDeque<(SocketAddr, Vec<u8>)>
inbound: VecDeque<(SocketAddr, Vec<u8>)>,
}
impl MockSocket {
@ -66,8 +95,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),
}
}
@ -82,12 +111,12 @@ impl MockSocket {
pub fn put_inbound(&mut self, from: SocketAddr, data: Vec<u8>) -> bool {
if !self.nat {
self.inbound.push_back((from, data));
return true
return true;
}
if let Some(timeout) = self.nat_peers.get(&from) {
if *timeout >= MockTimeSource::now() {
self.inbound.push_back((from, data));
return true
return true;
}
}
warn!("Sender {:?} is filtered out by NAT", from);
@ -106,8 +135,8 @@ impl AsRawFd for MockSocket {
}
impl Socket for MockSocket {
fn listen(addr: SocketAddr) -> Result<Self, io::Error> {
Ok(Self::new(addr))
fn listen(addr: &str) -> Result<Self, io::Error> {
Ok(Self::new(mapped_addr(parse_listen(addr, DEFAULT_PORT))))
}
fn receive(&mut self, buffer: &mut MsgBuffer) -> Result<SocketAddr, io::Error> {
@ -122,7 +151,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);
}
@ -132,6 +161,10 @@ impl Socket for MockSocket {
fn address(&self) -> Result<SocketAddr, io::Error> {
Ok(self.address)
}
fn create_port_forwarding(&self) -> Option<PortForwarding> {
None
}
}
#[cfg(feature = "bench")]

View File

@ -1,5 +1,10 @@
// 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;
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Copy)]
pub enum OldCryptoMethod {
@ -8,7 +13,7 @@ pub enum OldCryptoMethod {
#[serde(rename = "aes256")]
AES256,
#[serde(rename = "aes128")]
AES128
AES128,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Default)]
@ -52,7 +57,7 @@ pub struct OldConfigFile {
#[serde(alias = "statsd-prefix")]
pub statsd_prefix: Option<String>,
pub user: Option<String>,
pub group: Option<String>
pub group: Option<String>,
}
impl OldConfigFile {
@ -84,7 +89,7 @@ impl OldConfigFile {
interval: self.beacon_interval,
load: self.beacon_load,
store: self.beacon_store,
password: self.shared_key.clone()
password: self.shared_key.clone(),
}),
claims: self.subnets,
crypto: CryptoConfig {
@ -92,18 +97,19 @@ impl OldConfigFile {
password: Some(self.shared_key.unwrap_or_else(|| "none".to_string())),
private_key: None,
public_key: None,
trusted_keys: vec![]
trusted_keys: vec![],
},
device: Some(ConfigFileDevice {
fix_rp_filter: None,
name: self.device_name,
path: self.device_path,
type_: self.device_type
type_: self.device_type,
}),
group: self.group,
ifdown: self.ifdown,
ifup: self.ifup,
ip: None,
advertise_addresses: None,
keepalive: self.keepalive,
listen: self.listen.or(self.port.map(|p| format!("{}", p))),
mode: self.mode,
@ -112,12 +118,11 @@ impl OldConfigFile {
pid_file: self.pid_file,
port_forwarding: self.port_forwarding,
stats_file: self.stats_file,
statsd: Some(ConfigFileStatsd {
prefix: self.statsd_prefix,
server: self.statsd_server
}),
statsd: Some(ConfigFileStatsd { prefix: self.statsd_prefix, server: self.statsd_server }),
switch_timeout: self.dst_timeout,
user: self.user
user: self.user,
hook: None,
hooks: HashMap::new(),
}
}
}
}

View File

@ -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};
@ -23,6 +23,7 @@ impl Protocol for Frame {
/// # Errors
/// This method will fail when the given data is not a valid ethernet frame.
fn parse(data: &[u8]) -> Result<(Address, Address), Error> {
// HOT PATH
let mut cursor = Cursor::new(data);
let mut src = [0; 16];
let mut dst = [0; 16];
@ -42,7 +43,7 @@ impl Protocol for Frame {
// treat vlan id 0x000 as untagged
src.copy_within(2..8, 0);
dst.copy_within(2..8, 0);
return Ok((Address { data: src, len: 6 }, Address { data: dst, len: 6 }))
return Ok((Address { data: src, len: 6 }, Address { data: dst, len: 6 }));
}
Ok((Address { data: src, len: 8 }, Address { data: dst, len: 8 }))
} else {
@ -51,7 +52,6 @@ impl Protocol for Frame {
}
}
#[test]
fn decode_frame_without_vlan() {
let data = [6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 8];
@ -77,26 +77,6 @@ fn decode_invalid_frame() {
assert!(Frame::parse(&[6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 0x81, 0x00]).is_err());
}
#[cfg(feature = "bench")]
mod bench_ethernet {
use super::*;
use test::Bencher;
#[bench]
fn decode_ethernet(b: &mut Bencher) {
let data = [6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 8];
b.iter(|| Frame::parse(&data).unwrap());
b.bytes = 1400;
}
#[bench]
fn decode_ethernet_with_vlan(b: &mut Bencher) {
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];
b.iter(|| Frame::parse(&data).unwrap());
b.bytes = 1400;
}
}
/// An IP packet dissector
///
/// This dissector is able to extract the source and destination ip addresses of ipv4 packets and
@ -110,14 +90,15 @@ impl Protocol for Packet {
/// # Errors
/// This method will fail when the given data is not a valid ipv4 and ipv6 packet.
fn parse(data: &[u8]) -> Result<(Address, Address), Error> {
// HOT PATH
if data.is_empty() {
return Err(Error::Parse("Empty header"))
return Err(Error::Parse("Empty header"));
}
let version = data[0] >> 4;
match version {
4 => {
if data.len() < 20 {
return Err(Error::Parse("Truncated IPv4 header"))
return Err(Error::Parse("Truncated IPv4 header"));
}
let src = Address::read_from_fixed(&data[12..], 4)?;
let dst = Address::read_from_fixed(&data[16..], 4)?;
@ -125,18 +106,17 @@ impl Protocol for Packet {
}
6 => {
if data.len() < 40 {
return Err(Error::Parse("Truncated IPv6 header"))
return Err(Error::Parse("Truncated IPv6 header"));
}
let src = Address::read_from_fixed(&data[8..], 16)?;
let dst = Address::read_from_fixed(&data[24..], 16)?;
Ok((src, dst))
}
_ => Err(Error::Parse("Invalid IP protocol version"))
_ => Err(Error::Parse("Invalid IP protocol version")),
}
}
}
#[test]
fn decode_ipv4_packet() {
let data = [0x40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 168, 1, 1, 192, 168, 1, 2];
@ -149,7 +129,7 @@ fn decode_ipv4_packet() {
fn decode_ipv6_packet() {
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
4, 3, 2, 1,
];
let (src, dst) = Packet::parse(&data).unwrap();
assert_eq!(src, Address { data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6], len: 16 });
@ -177,27 +157,3 @@ fn decode_invalid_packet() {
])
.is_err());
}
#[cfg(feature = "bench")]
mod bench_ip {
use super::*;
use test::Bencher;
#[bench]
fn decode_ipv4(b: &mut Bencher) {
let data = [0x40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 168, 1, 1, 192, 168, 1, 2];
b.iter(|| Packet::parse(&data).unwrap());
b.bytes = 1400;
}
#[bench]
fn decode_ipv6(b: &mut Bencher) {
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
];
b.iter(|| Packet::parse(&data).unwrap());
b.bytes = 1400;
}
}

View File

@ -1,50 +1,43 @@
// 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::device::Device;
use std::{io, os::unix::io::RawFd};
use super::WaitResult;
use crate::{device::Type, net::Socket};
pub struct EpollWait {
poll_fd: RawFd,
event: libc::epoll_event,
socket: RawFd,
device: RawFd,
timeout: u32
timeout: u32,
}
impl EpollWait {
pub fn new<S: Socket>(socket: &S, device: &dyn Device, timeout: u32) -> io::Result<Self> {
pub fn new(socket: RawFd, device: RawFd, timeout: u32) -> io::Result<Self> {
Self::create(socket, device, timeout, libc::EPOLLIN as u32)
}
pub fn testing<S: Socket>(socket: &S, device: &dyn Device, timeout: u32) -> io::Result<Self> {
pub fn testing(socket: RawFd, device: RawFd, timeout: u32) -> io::Result<Self> {
Self::create(socket, device, timeout, (libc::EPOLLIN | libc::EPOLLOUT) as u32)
}
fn create<S: Socket>(socket: &S, device: &dyn Device, timeout: u32, flags: u32) -> io::Result<Self> {
fn create(socket: RawFd, device: RawFd, timeout: u32, flags: u32) -> io::Result<Self> {
let mut event = libc::epoll_event { u64: 0, events: 0 };
let poll_fd = unsafe { libc::epoll_create(3) };
if poll_fd == -1 {
return Err(io::Error::last_os_error())
return Err(io::Error::last_os_error());
}
let raw_fds = if device.get_type() != Type::Dummy {
vec![socket.as_raw_fd(), device.as_raw_fd()]
} else {
vec![socket.as_raw_fd()]
};
for fd in raw_fds {
event.u64 = fd as u64;
for fd in &[socket, device] {
event.u64 = *fd as u64;
event.events = flags;
let res = unsafe { libc::epoll_ctl(poll_fd, libc::EPOLL_CTL_ADD, fd, &mut event) };
let res = unsafe { libc::epoll_ctl(poll_fd, libc::EPOLL_CTL_ADD, *fd, &mut event) };
if res == -1 {
return Err(io::Error::last_os_error())
return Err(io::Error::last_os_error());
}
}
Ok(Self { poll_fd, event, socket: socket.as_raw_fd(), device: device.as_raw_fd(), timeout })
Ok(Self { poll_fd, event, socket, device, timeout })
}
}
@ -70,7 +63,7 @@ impl Iterator for EpollWait {
unreachable!()
}
}
_ => unreachable!()
_ => unreachable!(),
})
}
}

View File

@ -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"))]
@ -8,12 +8,11 @@ mod epoll;
#[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)
Error(io::Error),
}

View File

@ -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")]
@ -19,7 +19,7 @@ mod internal {
pub internal_addr: SocketAddrV4,
pub external_addr: SocketAddrV4,
gateway: Gateway,
pub next_extension: Option<Time>
pub next_extension: Option<Time>,
}
impl PortForwarding {
@ -32,11 +32,11 @@ mod internal {
if err.kind() == io::ErrorKind::WouldBlock {
// Why this code?
info!("Port-forwarding: no router found");
return None
return None;
}
}
error!("Port-forwarding: failed to find router: {}", err);
return None
return None;
}
};
debug!("Port-forwarding: found router at {}", gateway.addr);
@ -46,7 +46,7 @@ mod internal {
Ok(ip) => ip,
Err(err) => {
error!("Port-forwarding: failed to obtain external IP: {}", err);
return None
return None;
}
};
if let Ok((port, timeout)) = Self::get_any_forwarding(&gateway, internal_addr, port) {
@ -64,19 +64,19 @@ mod internal {
fn get_any_forwarding(gateway: &Gateway, addr: SocketAddrV4, port: u16) -> Result<(u16, u32), ()> {
if let Ok(a) = Self::get_forwarding(gateway, addr, port) {
return Ok(a)
return Ok(a);
}
if let Ok(a) = Self::get_forwarding(gateway, addr, 0) {
return Ok(a)
return Ok(a);
}
for i in 1..5 {
if let Ok(a) = Self::get_forwarding(gateway, addr, port + i) {
return Ok(a)
return Ok(a);
}
}
for _ in 0..5 {
if let Ok(a) = Self::get_forwarding(gateway, addr, rand::random()) {
return Ok(a)
return Ok(a);
}
}
warn!("Failed to activate port forwarding");
@ -125,20 +125,20 @@ mod internal {
pub fn check_extend(&mut self) {
if let Some(deadline) = self.next_extension {
if deadline > SystemTimeSource::now() {
return
return;
}
} else {
return
return;
}
match self.gateway.add_port(
PortMappingProtocol::UDP,
self.external_addr.port(),
self.internal_addr,
LEASE_TIME,
DESCRIPTION
DESCRIPTION,
) {
Ok(()) => debug!("Port-forwarding: extended port forwarding"),
Err(err) => debug!("Port-forwarding: failed to extend port forwarding: {}", err)
Err(err) => debug!("Port-forwarding: failed to extend port forwarding: {}", err),
};
self.next_extension = Some(SystemTimeSource::now() + Time::from(LEASE_TIME) - 60);
}
@ -146,7 +146,7 @@ mod internal {
fn deactivate(&self) {
match self.gateway.remove_port(PortMappingProtocol::UDP, self.external_addr.port()) {
Ok(()) => info!("Port-forwarding: successfully deactivated port forwarding"),
Err(err) => debug!("Port-forwarding: failed to deactivate port forwarding: {}", err)
Err(err) => debug!("Port-forwarding: failed to deactivate port forwarding: {}", err),
}
}

View File

@ -1,30 +1,28 @@
// 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;
use std::{
cmp::min, collections::HashMap, hash::BuildHasherDefault, io, io::Write, marker::PhantomData, net::SocketAddr
cmp::min, collections::HashMap, hash::BuildHasherDefault, io, io::Write, marker::PhantomData, net::SocketAddr,
};
use crate::{
types::{Address, Range, RangeList},
util::{addr_nice, Duration, Time, TimeSource}
util::{addr_nice, Duration, Time, TimeSource},
};
type Hash = BuildHasherDefault<FnvHasher>;
struct CacheValue {
peer: SocketAddr,
timeout: Time
timeout: Time,
}
struct ClaimEntry {
peer: SocketAddr,
claim: Range,
timeout: Time
timeout: Time,
}
pub struct ClaimTable<TS: TimeSource> {
@ -32,7 +30,7 @@ pub struct ClaimTable<TS: TimeSource> {
cache_timeout: Duration,
claims: Vec<ClaimEntry>,
claim_timeout: Duration,
_dummy: PhantomData<TS>
_dummy: PhantomData<TS>,
}
impl<TS: TimeSource> ClaimTable<TS> {
@ -41,10 +39,16 @@ impl<TS: TimeSource> ClaimTable<TS> {
}
pub fn cache(&mut self, addr: Address, peer: SocketAddr) {
// HOT PATH
self.cache.insert(addr, CacheValue { peer, timeout: TS::now() + self.cache_timeout as Time });
}
pub fn clear_cache(&mut self) {
self.cache.clear()
}
pub fn set_claims(&mut self, peer: SocketAddr, mut claims: RangeList) {
let mut removed_claim = false;
for entry in &mut self.claims {
if entry.peer == peer {
let pos = claims.iter().position(|r| r == &entry.claim);
@ -52,19 +56,22 @@ impl<TS: TimeSource> ClaimTable<TS> {
entry.timeout = TS::now() + self.claim_timeout as Time;
claims.swap_remove(pos);
if claims.is_empty() {
break
break;
}
} else {
entry.timeout = 0
entry.timeout = 0;
removed_claim = true;
}
}
}
for claim in claims {
self.claims.push(ClaimEntry { peer, claim, timeout: TS::now() + self.claim_timeout as Time })
}
for entry in self.cache.values_mut() {
if entry.peer == peer {
entry.timeout = 0
if removed_claim {
for entry in self.cache.values_mut() {
if entry.peer == peer {
entry.timeout = 0
}
}
}
self.housekeep()
@ -85,9 +92,11 @@ impl<TS: TimeSource> ClaimTable<TS> {
}
pub fn lookup(&mut self, addr: Address) -> Option<SocketAddr> {
// HOT PATH
if let Some(entry) = self.cache.get(&addr) {
return Some(entry.peer)
return Some(entry.peer);
}
// COLD PATH
let mut found = None;
let mut prefix_len = -1;
for entry in &self.claims {
@ -97,11 +106,11 @@ impl<TS: TimeSource> ClaimTable<TS> {
}
}
if let Some(entry) = found {
self.cache.insert(addr, CacheValue {
peer: entry.peer,
timeout: min(TS::now() + self.cache_timeout as Time, entry.timeout)
});
return Some(entry.peer)
self.cache.insert(
addr,
CacheValue { peer: entry.peer, timeout: min(TS::now() + self.cache_timeout as Time, entry.timeout) },
);
return Some(entry.peer);
}
None
}
@ -149,36 +158,3 @@ impl<TS: TimeSource> ClaimTable<TS> {
}
// TODO: test
#[cfg(feature = "bench")]
mod bench {
use super::*;
use crate::util::MockTimeSource;
use smallvec::smallvec;
use std::str::FromStr;
use test::Bencher;
#[bench]
fn lookup_warm(b: &mut Bencher) {
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());
b.iter(|| table.lookup(addr));
b.bytes = 1400;
}
#[bench]
fn lookup_cold(b: &mut Bencher) {
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()
]);
b.iter(|| {
table.cache.clear();
table.lookup(addr)
});
b.bytes = 1400;
}
}

210
src/tests/common.rs Normal file
View File

@ -0,0 +1,210 @@
// 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},
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();
}
}

View File

@ -1,217 +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::{IpAddr, Ipv6Addr, 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 = SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), self.next_port);
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, MockDevice::new(), None, None);
DebugLogger::set_node(0);
self.nodes.insert(config.listen, node);
config.listen
}
#[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();
}
}
mod peers;

View File

@ -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() {

View File

@ -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() {

View File

@ -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() {

View File

@ -1,21 +1,20 @@
// 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::{
collections::HashMap,
io::{self, Write},
net::SocketAddr,
ops::AddAssign
ops::AddAssign,
};
use super::{
cloud::{Hash, STATS_INTERVAL},
types::Address,
util::{addr_nice, Bytes}
util::{addr_nice, Bytes},
};
#[derive(Default)]
pub struct TrafficEntry {
pub out_bytes_total: u64,
@ -26,7 +25,7 @@ pub struct TrafficEntry {
pub in_packets_total: usize,
pub in_bytes: u64,
pub in_packets: usize,
pub idle_periods: usize
pub idle_periods: usize,
}
impl AddAssign<&TrafficEntry> for TrafficEntry {
@ -72,33 +71,36 @@ impl TrafficEntry {
}
}
#[derive(Default)]
pub struct TrafficStats {
peers: HashMap<SocketAddr, TrafficEntry, Hash>,
payload: HashMap<(Address, Address), TrafficEntry, Hash>,
pub dropped: TrafficEntry
pub dropped: TrafficEntry,
}
impl TrafficStats {
#[inline]
pub fn count_out_traffic(&mut self, peer: SocketAddr, bytes: usize) {
self.peers.entry(peer).or_insert_with(TrafficEntry::default).count_out(bytes);
// HOT PATH
self.peers.entry(peer).or_default().count_out(bytes);
}
#[inline]
pub fn count_in_traffic(&mut self, peer: SocketAddr, bytes: usize) {
self.peers.entry(peer).or_insert_with(TrafficEntry::default).count_in(bytes);
// HOT PATH
self.peers.entry(peer).or_default().count_in(bytes);
}
#[inline]
pub fn count_out_payload(&mut self, remote: Address, local: Address, bytes: usize) {
self.payload.entry((remote, local)).or_insert_with(TrafficEntry::default).count_out(bytes);
// HOT PATH
self.payload.entry((remote, local)).or_default().count_out(bytes);
}
#[inline]
pub fn count_in_payload(&mut self, remote: Address, local: Address, bytes: usize) {
self.payload.entry((remote, local)).or_insert_with(TrafficEntry::default).count_in(bytes);
// HOT PATH
self.payload.entry((remote, local)).or_default().count_in(bytes);
}
pub fn count_invalid_protocol(&mut self, bytes: usize) {

View File

@ -1,10 +1,10 @@
// 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,
util::{bytes_to_hex, Encoder}
util::{bytes_to_hex, Encoder},
};
use byteorder::{ReadBytesExt, WriteBytesExt};
use smallvec::SmallVec;
@ -13,18 +13,17 @@ use std::{
hash::{Hash, Hasher},
io::{Read, Write},
net::{Ipv4Addr, Ipv6Addr},
str::FromStr
str::FromStr,
};
pub const NODE_ID_BYTES: usize = 16;
pub type NodeId = [u8; NODE_ID_BYTES];
#[derive(Eq, Clone, Copy)]
pub struct Address {
pub data: [u8; 16],
pub len: u8
pub len: u8,
}
impl Address {
@ -37,7 +36,7 @@ impl Address {
#[inline]
pub fn read_from_fixed<R: Read>(mut r: R, len: u8) -> Result<Address, Error> {
if len > 16 {
return Err(Error::Parse("Invalid address, too long"))
return Err(Error::Parse("Invalid address, too long"));
}
let mut data = [0; 16];
r.read_exact(&mut data[..len as usize]).map_err(|_| Error::Parse("Address too short"))?;
@ -57,7 +56,6 @@ impl Address {
}
}
impl PartialEq for Address {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
@ -65,7 +63,6 @@ impl PartialEq for Address {
}
}
impl Hash for Address {
#[inline]
fn hash<H: Hasher>(&self, hasher: &mut H) {
@ -73,7 +70,6 @@ impl Hash for Address {
}
}
impl fmt::Display for Address {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let d = &self.data;
@ -108,7 +104,7 @@ impl FromStr for Address {
let ip = addr.octets();
let mut res = [0; 16];
res[0..4].copy_from_slice(&ip);
return Ok(Address { data: res, len: 4 })
return Ok(Address { data: res, len: 4 });
}
if let Ok(addr) = Ipv6Addr::from_str(text) {
let segments = addr.segments();
@ -116,7 +112,7 @@ impl FromStr for Address {
for i in 0..8 {
Encoder::write_u16(segments[i], &mut res[2 * i..]);
}
return Ok(Address { data: res, len: 16 })
return Ok(Address { data: res, len: 16 });
}
let parts: SmallVec<[&str; 10]> = text.split(':').collect();
if parts.len() == 6 {
@ -124,17 +120,16 @@ impl FromStr for Address {
for i in 0..6 {
bytes[i] = u8::from_str_radix(parts[i], 16).map_err(|_| Error::Parse("Failed to parse mac"))?;
}
return Ok(Address { data: bytes, len: 6 })
return Ok(Address { data: bytes, len: 6 });
}
Err(Error::Parse("Failed to parse address"))
}
}
#[derive(PartialEq, Eq, Hash, Clone, Copy)]
pub struct Range {
pub base: Address,
pub prefix_len: u8
pub prefix_len: u8,
}
pub type RangeList = SmallVec<[Range; 4]>;
@ -142,14 +137,14 @@ pub type RangeList = SmallVec<[Range; 4]>;
impl Range {
pub fn matches(&self, addr: Address) -> bool {
if self.base.len != addr.len {
return false
return false;
}
let mut match_len = 0;
for i in 0..addr.len as usize {
let m = addr.data[i] ^ self.base.data[i];
match_len += m.leading_zeros() as u8;
if m != 0 {
break
break;
}
}
match_len >= self.prefix_len
@ -175,7 +170,7 @@ impl FromStr for Range {
fn from_str(text: &str) -> Result<Self, Self::Err> {
let pos = match text.find('/') {
Some(pos) => pos,
None => return Err(Error::Parse("Invalid range format"))
None => return Err(Error::Parse("Invalid range format")),
};
let prefix_len = u8::from_str(&text[pos + 1..]).map_err(|_| Error::Parse("Failed to parse prefix length"))?;
let base = Address::from_str(&text[..pos])?;
@ -195,7 +190,6 @@ impl fmt::Debug for Range {
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
pub enum Mode {
#[serde(rename = "normal")]
@ -205,7 +199,7 @@ pub enum Mode {
#[serde(rename = "switch")]
Switch,
#[serde(rename = "router")]
Router
Router,
}
impl fmt::Display for Mode {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
@ -213,7 +207,7 @@ impl fmt::Display for Mode {
Mode::Normal => write!(formatter, "normal"),
Mode::Hub => write!(formatter, "hub"),
Mode::Switch => write!(formatter, "switch"),
Mode::Router => write!(formatter, "router")
Mode::Router => write!(formatter, "router"),
}
}
}
@ -226,12 +220,11 @@ impl FromStr for Mode {
"hub" => Self::Hub,
"switch" => Self::Switch,
"router" => Self::Router,
_ => return Err("Unknown mode")
_ => return Err("Unknown mode"),
})
}
}
#[cfg(test)]
mod tests {

View File

@ -1,32 +1,32 @@
// 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;
use std::{
fmt,
net::{Ipv4Addr, SocketAddr, ToSocketAddrs, UdpSocket},
sync::atomic::{AtomicIsize, Ordering}
sync::atomic::{AtomicIsize, Ordering},
};
use crate::error::Error;
#[cfg(not(target_os = "linux"))] use time;
#[cfg(not(target_os = "linux"))]
use time;
use signal::{trap::Trap, Signal};
use smallvec::SmallVec;
use std::time::Instant;
pub type Duration = u32;
pub type Time = i64;
#[derive(Clone)]
pub struct MsgBuffer {
space_before: usize,
buffer: [u8; 65535],
start: usize,
end: usize
end: usize,
}
impl MsgBuffer {
@ -98,7 +98,6 @@ impl MsgBuffer {
}
}
const HEX_CHARS: &[u8] = b"0123456789abcdef";
pub fn bytes_to_hex(bytes: &[u8]) -> String {
@ -113,13 +112,12 @@ pub fn bytes_to_hex(bytes: &[u8]) -> String {
pub fn addr_nice(addr: SocketAddr) -> SocketAddr {
if let SocketAddr::V6(v6addr) = addr {
if let Some(ip) = v6addr.ip().to_ipv4() {
return (ip, addr.port()).into()
return (ip, addr.port()).into();
}
}
addr
}
pub struct Encoder;
impl Encoder {
@ -172,7 +170,6 @@ impl Encoder {
}
}
macro_rules! fail {
($format:expr) => ( {
use std::process;
@ -215,17 +212,14 @@ pub fn get_internal_ip() -> Ipv4Addr {
}
}
#[allow(unknown_lints, clippy::needless_pass_by_value)]
pub fn resolve<Addr: ToSocketAddrs + fmt::Debug>(addr: Addr) -> Result<SmallVec<[SocketAddr; 3]>, Error> {
pub fn resolve<Addr: ToSocketAddrs + fmt::Debug>(addr: Addr) -> Result<SmallVec<[SocketAddr; 4]>, Error> {
let mut addrs =
addr.to_socket_addrs().map_err(|_| Error::NameUnresolvable(format!("{:?}", addr)))?.collect::<SmallVec<_>>();
// Try IPv4 first as it usually is faster
addrs.sort_by_key(|addr| {
match *addr {
SocketAddr::V4(_) => 4,
SocketAddr::V6(_) => 6
}
addrs.sort_by_key(|addr| match *addr {
SocketAddr::V4(_) => 4,
SocketAddr::V6(_) => 6,
});
// Remove duplicates in addrs (why are there duplicates???)
addrs.dedup();
@ -239,7 +233,6 @@ macro_rules! addr {
}};
}
pub struct Bytes(pub u64);
impl fmt::Display for Bytes {
@ -248,31 +241,30 @@ impl fmt::Display for Bytes {
if size >= 512.0 {
size /= 1024.0;
} else {
return write!(formatter, "{:.0} B", size)
return write!(formatter, "{:.0} B", size);
}
if size >= 512.0 {
size /= 1024.0;
} else {
return write!(formatter, "{:.1} KiB", size)
return write!(formatter, "{:.1} KiB", size);
}
if size >= 512.0 {
size /= 1024.0;
} else {
return write!(formatter, "{:.1} MiB", size)
return write!(formatter, "{:.1} MiB", size);
}
if size >= 512.0 {
size /= 1024.0;
} else {
return write!(formatter, "{:.1} GiB", size)
return write!(formatter, "{:.1} GiB", size);
}
write!(formatter, "{:.1} TiB", size)
}
}
pub struct CtrlC {
dummy_time: Instant,
trap: Trap
trap: Trap,
}
impl CtrlC {
@ -293,7 +285,6 @@ impl Default for CtrlC {
}
}
pub trait TimeSource: Sync + Copy + Send + 'static {
fn now() -> Time;
}
@ -336,7 +327,6 @@ impl TimeSource for MockTimeSource {
}
}
/// Helper function that multiplies the base62 data in buf[0..buflen] by 16 and adds m to it
fn base62_add_mult_16(buf: &mut [u8], mut buflen: usize, m: u8) -> usize {
let mut d: usize = m as usize;
@ -356,7 +346,7 @@ fn base62_add_mult_16(buf: &mut [u8], mut buflen: usize, m: u8) -> usize {
const BASE62: [char; 62] = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
];
pub fn to_base62(data: &[u8]) -> String {
@ -379,10 +369,10 @@ pub fn from_base62(data: &str) -> Result<Vec<u8>, char> {
let mut buf = Vec::with_capacity(data.len() / 2 + data.len() / 4);
for c in data.chars() {
let mut val = match c {
'0'..='9' => ((c as usize) % ('0' as usize)),
'0'..='9' => (c as usize) % ('0' as usize),
'A'..='Z' => ((c as usize) % ('A' as usize)) + 10,
'a'..='z' => ((c as usize) % ('a' as usize)) + 36,
_ => return Err(c)
_ => return Err(c),
};
for item in &mut buf {
val += *item as usize * 62;
@ -397,11 +387,10 @@ pub fn from_base62(data: &str) -> Result<Vec<u8>, char> {
Ok(buf)
}
#[derive(Default)]
pub struct StatsdMsg {
entries: Vec<String>,
key: Vec<String>
key: Vec<String>,
}
impl StatsdMsg {
@ -426,6 +415,16 @@ impl StatsdMsg {
}
}
pub fn run_cmd(mut cmd: Command) {
match cmd.status() {
Ok(status) => {
if !status.success() {
error!("Command returned error: {:?}", status.code())
}
}
Err(e) => error!("Failed to execute command {:?}: {}", cmd, e),
}
}
#[test]
fn base62() {

509
src/wizard.rs Normal file
View File

@ -0,0 +1,509 @@
use crate::{config::Config, crypto::Crypto, device, types::Mode};
use dialoguer::{theme::ColorfulTheme, Confirm, Input, MultiSelect, Password, Select};
use ring::aead;
use std::{collections::HashMap, fs, io, os::unix::fs::PermissionsExt, path::Path};
const MODE_SIMPLE: usize = 0;
const MODE_ADVANCED: usize = 1;
const MODE_EXPERT: usize = 2;
fn str_list(s: String) -> Vec<String> {
if s.is_empty() {
vec![]
} else {
s.split(',').map(|k| k.trim().to_string()).collect()
}
}
fn str_opt(s: String) -> Option<String> {
if s.is_empty() {
None
} else {
Some(s)
}
}
fn configure_connectivity(config: &mut Config, mode: usize, theme: &ColorfulTheme) -> Result<(), dialoguer::Error> {
if mode >= MODE_ADVANCED {
config.listen =
Input::with_theme(theme).with_prompt("Listen address").default(config.listen.clone()).interact_text()?;
}
config.peers = str_list(
Input::with_theme(theme)
.with_prompt("Peer addresses (comma separated)")
.default(config.peers.join(","))
.interact_text()?,
);
if mode >= MODE_ADVANCED {
config.port_forwarding = Confirm::with_theme(theme)
.with_prompt("Enable automatic port forwarding?")
.default(config.port_forwarding)
.interact()?;
}
if mode == MODE_EXPERT {
config.advertise_addresses = str_list(
Input::with_theme(theme)
.with_prompt("Advertise addresses (comma separated)")
.default(config.advertise_addresses.join(","))
.interact_text()?,
);
config.peer_timeout = Input::with_theme(theme)
.with_prompt("Peer timeout (in seconds)")
.default(config.peer_timeout)
.interact_text()?;
let val = Input::with_theme(theme)
.with_prompt("Keepalive interval (in seconds, 0 for default)")
.default(config.keepalive.unwrap_or_default())
.interact_text()?;
config.keepalive = if val == 0 { None } else { Some(val) };
}
Ok(())
}
fn configure_crypto(config: &mut Config, mode: usize, theme: &ColorfulTheme) -> Result<(), dialoguer::Error> {
if (config.crypto.password.is_some() || config.crypto.private_key.is_some())
&& !Confirm::with_theme(theme).with_prompt("Create new crypto config?").default(false).interact()?
{
return Ok(());
}
let mut use_password = true;
if mode >= MODE_ADVANCED {
use_password = Select::with_theme(theme)
.with_prompt("Crypto configuration method")
.items(&["Simple (Password)", "Complex (Key pair)"])
.default(if config.crypto.private_key.is_some() { 1 } else { 0 })
.interact()?
== 0
}
if use_password {
config.crypto.password = Some(
Password::with_theme(theme)
.with_prompt("Password")
.with_confirmation("Confirm password", "Passwords do not match")
.interact()?,
);
config.crypto.private_key = None;
config.crypto.public_key = None;
config.crypto.trusted_keys = vec![];
} else {
config.crypto.password = None;
let (priv_key, pub_key) = match Select::with_theme(theme)
.with_prompt("Specify key pair")
.items(&["Generate new key pair", "Enter private key", "Generate from password"])
.default(0)
.interact()?
{
0 => {
let (priv_key, pub_key) = Crypto::generate_keypair(None);
info!("Private key: {}", priv_key);
info!("Public key: {}", pub_key);
(priv_key, pub_key)
}
1 => {
let priv_key = Password::with_theme(theme)
.with_prompt("Private key")
.with_confirmation("Confirm private key", "Keys do not match")
.interact()?;
let pub_key = try_fail!(Crypto::public_key_from_private_key(&priv_key), "Invalid private key: {:?}");
info!("Public key: {}", pub_key);
(priv_key, pub_key)
}
2 => {
let password = Password::with_theme(theme)
.with_prompt("Password")
.with_confirmation("Confirm password", "Passwords do not match")
.interact()?;
let (priv_key, pub_key) = Crypto::generate_keypair(Some(&password));
info!("Private key: {}", priv_key);
info!("Public key: {}", pub_key);
(priv_key, pub_key)
}
_ => unreachable!(),
};
config.crypto.trusted_keys = str_list(
Input::with_theme(theme)
.with_prompt("Trusted keys (public keys, comma separated)")
.default(pub_key.clone())
.interact_text()?,
);
config.crypto.private_key = Some(priv_key);
config.crypto.public_key = Some(pub_key);
}
if mode == MODE_EXPERT {
let (unencrypted, allowed_algos) = Crypto::parse_algorithms(&config.crypto.algorithms)
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid crypto algorithms"))?;
let algos = MultiSelect::with_theme(theme)
.with_prompt("Allowed encryption algorithms (select multiple)")
.items_checked(&[
("Unencrypted (dangerous)", unencrypted),
("AES-128 in GCM mode", allowed_algos.contains(&&aead::AES_128_GCM)),
("AES-256 in GCM mode", allowed_algos.contains(&&aead::AES_256_GCM)),
("ChaCha20-Poly1305 (RFC 7539)", allowed_algos.contains(&&aead::CHACHA20_POLY1305)),
])
.interact()?;
config.crypto.algorithms = vec![];
for (id, name) in &[(0, "PLAIN"), (1, "AES128"), (2, "AES256"), (3, "CHACHA20")] {
if algos.contains(id) {
config.crypto.algorithms.push(name.to_string());
}
}
}
Ok(())
}
fn configure_device(config: &mut Config, mode: usize, theme: &ColorfulTheme) -> Result<(), dialoguer::Error> {
if mode >= MODE_ADVANCED {
config.device_type = match Select::with_theme(theme)
.with_prompt("Device type")
.items(&["Tun (IP based)", "Tap (Ethernet based)"])
.default(if config.device_type == device::Type::Tun { 0 } else { 1 })
.interact()?
{
0 => device::Type::Tun,
1 => device::Type::Tap,
_ => unreachable!(),
}
}
if mode == MODE_EXPERT {
config.device_name =
Input::with_theme(theme).with_prompt("Device name").default(config.device_name.clone()).interact_text()?;
config.device_path = str_opt(
Input::with_theme(theme)
.with_prompt("Device path (empty for default)")
.default(config.device_path.as_ref().cloned().unwrap_or_default())
.interact_text()?,
);
config.fix_rp_filter = Confirm::with_theme(theme)
.with_prompt("Automatically fix insecure rp_filter settings")
.default(config.fix_rp_filter)
.interact()?;
config.mode = match Select::with_theme(theme)
.with_prompt("Operation mode")
.items(&["Normal", "Router", "Switch", "Hub"])
.default(match config.mode {
Mode::Normal => 0,
Mode::Router => 1,
Mode::Switch => 2,
Mode::Hub => 3,
})
.interact()?
{
0 => Mode::Normal,
1 => Mode::Router,
2 => Mode::Switch,
3 => Mode::Hub,
_ => unreachable!(),
};
if config.mode == Mode::Switch {
config.switch_timeout = Input::with_theme(theme)
.with_prompt("Switch timeout (in seconds")
.default(config.switch_timeout)
.interact_text()?;
}
}
Ok(())
}
fn configure_addresses(config: &mut Config, mode: usize, theme: &ColorfulTheme) -> Result<(), dialoguer::Error> {
config.ip = str_opt(
Input::with_theme(theme)
.with_prompt("Virtual IP address (e.g. 10.0.0.1, leave empty for none)")
.allow_empty(true)
.default(config.ip.as_ref().cloned().unwrap_or_default())
.interact_text()?,
);
if config.device_type == device::Type::Tun {
if mode >= MODE_ADVANCED {
config.auto_claim = Confirm::with_theme(theme)
.with_prompt("Automatically claim IP set on virtual interface?")
.default(config.auto_claim)
.interact()?;
}
if mode == MODE_EXPERT {
config.claims = str_list(
Input::with_theme(theme)
.with_prompt("Claim additional addresses (e.g. 10.0.0.0/24, comma separated, leave empty for none)")
.allow_empty(true)
.default(config.claims.join(","))
.interact_text()?,
);
}
} else {
config.claims = vec![];
}
if mode == MODE_EXPERT {
config.ifup = str_opt(
Input::with_theme(theme)
.with_prompt("Interface setup command (leave empty for none)")
.allow_empty(true)
.default(config.ifup.as_ref().cloned().unwrap_or_default())
.interact_text()?,
);
config.ifdown = str_opt(
Input::with_theme(theme)
.with_prompt("Interface tear down command (leave empty for none)")
.allow_empty(true)
.default(config.ifdown.as_ref().cloned().unwrap_or_default())
.interact_text()?,
);
}
Ok(())
}
fn configure_beacon(config: &mut Config, mode: usize, theme: &ColorfulTheme) -> Result<(), dialoguer::Error> {
if mode == MODE_EXPERT
&& Confirm::with_theme(theme)
.with_prompt("Configure beacons?")
.default(config.beacon_load.is_some() || config.beacon_store.is_some())
.interact()?
{
config.beacon_store = match Select::with_theme(theme)
.with_prompt("How to store beacons")
.items(&["Do not store beacons", "Store to file", "Execute command"])
.default(if let Some(v) = &config.beacon_store {
if v.starts_with('|') {
2
} else {
1
}
} else {
0
})
.interact()?
{
0 => None,
1 => Some(
Input::with_theme(theme)
.with_prompt("File path")
.default(config.beacon_store.clone().unwrap_or_default())
.interact_text()?,
),
2 => Some(format!(
"|{}",
Input::<String>::with_theme(theme)
.with_prompt("Command")
.default(config.beacon_store.clone().unwrap_or_default().trim_start_matches('|').to_string())
.interact_text()?
)),
_ => unreachable!(),
};
config.beacon_load = match Select::with_theme(theme)
.with_prompt("How to load beacons")
.items(&["Do not load beacons", "Load from file", "Execute command"])
.default(if let Some(v) = &config.beacon_load {
if v.starts_with('|') {
2
} else {
1
}
} else {
0
})
.interact()?
{
0 => None,
1 => Some(
Input::with_theme(theme)
.with_prompt("File path")
.default(config.beacon_load.clone().unwrap_or_default())
.interact_text()?,
),
2 => Some(format!(
"|{}",
Input::<String>::with_theme(theme)
.with_prompt("Command")
.default(config.beacon_load.clone().unwrap_or_default().trim_start_matches('|').to_string())
.interact_text()?
)),
_ => unreachable!(),
};
config.beacon_interval = Input::with_theme(theme)
.with_prompt("Beacon interval (in seconds)")
.default(config.beacon_interval)
.interact_text()?;
config.beacon_password = str_opt(
Password::with_theme(theme)
.with_prompt("Beacon password (leave empty for none)")
.with_confirmation("Confirm password", "Passwords do not match")
.allow_empty_password(true)
.interact()?,
);
}
Ok(())
}
fn configure_stats(config: &mut Config, mode: usize, theme: &ColorfulTheme) -> Result<(), dialoguer::Error> {
if mode >= MODE_ADVANCED {
config.stats_file = str_opt(
Input::with_theme(theme)
.with_prompt("Write stats to file (empty to disable)")
.default(config.stats_file.clone().unwrap_or_default())
.allow_empty(true)
.interact_text()?,
);
}
if mode == MODE_EXPERT {
if Confirm::with_theme(theme)
.with_prompt("Send statistics to statsd server?")
.default(config.statsd_server.is_some())
.interact()?
{
config.statsd_server = str_opt(
Input::with_theme(theme)
.with_prompt("Statsd server URL")
.default(config.statsd_server.clone().unwrap_or_default())
.allow_empty(true)
.interact_text()?,
);
config.statsd_prefix = str_opt(
Input::with_theme(theme)
.with_prompt("Statsd prefix")
.default(config.statsd_prefix.clone().unwrap_or_default())
.allow_empty(true)
.interact_text()?,
);
} else {
config.statsd_server = None;
}
}
Ok(())
}
fn configure_process(config: &mut Config, mode: usize, theme: &ColorfulTheme) -> Result<(), dialoguer::Error> {
if mode == MODE_EXPERT {
config.user = str_opt(
Input::with_theme(theme)
.with_prompt("Run as different user (empty to disable)")
.default(config.user.clone().unwrap_or_default())
.allow_empty(true)
.interact_text()?,
);
config.group = str_opt(
Input::with_theme(theme)
.with_prompt("Run as different group (empty to disable)")
.default(config.group.clone().unwrap_or_default())
.allow_empty(true)
.interact_text()?,
);
config.pid_file = str_opt(
Input::with_theme(theme)
.with_prompt("Write process id to file (empty to disable)")
.default(config.pid_file.clone().unwrap_or_default())
.allow_empty(true)
.interact_text()?,
);
}
Ok(())
}
fn configure_hooks(config: &mut Config, mode: usize, theme: &ColorfulTheme) -> Result<(), dialoguer::Error> {
if mode == MODE_EXPERT {
if Confirm::with_theme(theme)
.with_prompt("Set hooks to react on events?")
.default(config.hook.is_some() || !config.hooks.is_empty())
.interact()?
{
config.hook = str_opt(
Input::with_theme(theme)
.with_prompt("Command to execute for all events (empty to disable)")
.default(config.hook.clone().unwrap_or_default())
.allow_empty(true)
.interact_text()?,
);
let mut hooks: HashMap<String, String> = Default::default();
for event in &[
"peer_connecting",
"peer_connected",
"peer_disconnected",
"device_setup",
"device_configured",
"vpn_started",
"vpn_shutdown",
] {
if let Some(cmd) = str_opt(
Input::with_theme(theme)
.with_prompt(format!("Command to execute for event '{}' (empty to disable)", event))
.default(config.hooks.get(*event).cloned().unwrap_or_default())
.allow_empty(true)
.interact_text()?,
) {
hooks.insert(event.to_string(), cmd);
}
}
config.hooks = hooks;
} else {
config.hook = None;
config.hooks = Default::default();
}
}
Ok(())
}
pub fn configure(name: Option<String>) -> Result<(), dialoguer::Error> {
let theme = ColorfulTheme::default();
let name = if let Some(name) = name {
name
} else {
let mut names = vec![];
for file in fs::read_dir("/etc/vpncloud")? {
names.push(file?.path().file_stem().unwrap().to_str().unwrap().to_string());
}
let selection =
Select::with_theme(&theme).with_prompt("Which network?").item("New network").items(&names).interact()?;
if selection > 0 {
names[selection - 1].clone()
} else {
Input::with_theme(&theme).with_prompt("Network name").interact_text()?
}
};
let mut config = Config::default();
let file = Path::new("/etc/vpncloud").join(format!("{}.net", name));
if file.exists() {
let f = fs::File::open(&file)?;
let config_file = serde_yaml::from_reader(f)
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Failed to parse config file"))?;
config.merge_file(config_file);
}
if file.parent().unwrap().metadata()?.permissions().readonly() {
return Err(io::Error::new(io::ErrorKind::PermissionDenied, "Config file not writable").into());
}
loop {
let mode = Select::with_theme(&theme)
.with_prompt("Configuration mode")
.items(&["Simple (minimal options)", "Advanced (some more options)", "Expert (all options)"])
.default(MODE_SIMPLE)
.interact()?;
configure_connectivity(&mut config, mode, &theme)?;
configure_crypto(&mut config, mode, &theme)?;
configure_device(&mut config, mode, &theme)?;
configure_addresses(&mut config, mode, &theme)?;
configure_beacon(&mut config, mode, &theme)?;
configure_stats(&mut config, mode, &theme)?;
configure_process(&mut config, mode, &theme)?;
configure_hooks(&mut config, mode, &theme)?;
if Confirm::with_theme(&theme).with_prompt("Finish configuration?").default(true).interact()? {
break;
}
}
if Confirm::with_theme(&theme).with_prompt("Save config?").default(true).interact()? {
let config_file = config.into_config_file();
let f = fs::File::create(&file)?;
serde_yaml::to_writer(f, &config_file)
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Failed to parse config file"))?;
fs::set_permissions(file, fs::Permissions::from_mode(0o600))?;
println!();
println!("Use the following commands to control your VPN:");
println!(" start the VPN: sudo service vpncloud@{0} start", name);
println!(" stop the VPN: sudo service vpncloud@{0} stop", name);
println!(" get the status: sudo service vpncloud@{0} status", name);
println!(" add VPN to autostart: sudo systemctl enable vpncloud@{0}", name);
println!(" remove VPN from autostart: sudo systemctl disable vpncloud@{0}", name);
}
Ok(())
}

169
src/wsproxy.rs Normal file
View File

@ -0,0 +1,169 @@
// 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},
port_forwarding::PortForwarding,
util::MsgBuffer,
};
use byteorder::{NetworkEndian, ReadBytesExt, WriteBytesExt};
use std::{
io::{self, Cursor, Read, Write},
net::{Ipv6Addr, SocketAddr, SocketAddrV6, TcpListener, TcpStream, UdpSocket},
os::unix::io::{AsRawFd, RawFd},
thread::spawn,
};
use tungstenite::{connect, protocol::WebSocket, Message, accept, stream::{MaybeTlsStream, NoDelay}};
use url::Url;
macro_rules! io_error {
($val:expr, $format:expr) => ( {
$val.map_err(|err| io::Error::new(io::ErrorKind::Other, format!($format, err)))
} );
($val:expr, $format:expr, $( $arg:expr ),+) => ( {
$val.map_err(|err| io::Error::new(io::ErrorKind::Other, format!($format, $( $arg ),+, err)))
} );
}
fn write_addr<W: Write>(addr: SocketAddr, mut out: W) -> Result<(), io::Error> {
let addr = mapped_addr(addr);
match mapped_addr(addr) {
SocketAddr::V6(addr) => {
out.write_all(&addr.ip().octets())?;
out.write_u16::<NetworkEndian>(addr.port())?;
}
_ => unreachable!(),
}
Ok(())
}
fn read_addr<R: Read>(mut r: R) -> Result<SocketAddr, io::Error> {
let mut ip = [0u8; 16];
r.read_exact(&mut ip)?;
let port = r.read_u16::<NetworkEndian>()?;
let addr = SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::from(ip), port, 0, 0));
Ok(addr)
}
fn serve_proxy_connection(stream: TcpStream) -> Result<(), io::Error> {
let peer = stream.peer_addr()?;
info!("WS client {} connected", peer);
stream.set_nodelay(true)?;
let mut websocket = io_error!(accept(stream), "Failed to initialize websocket with {}: {}", peer)?;
let udpsocket = UdpSocket::bind("[::]:0")?;
let mut msg = Vec::with_capacity(18);
let mut addr = udpsocket.local_addr()?;
info!("Listening on {} for peer {}", addr, peer);
addr.set_ip(get_ip());
write_addr(addr, &mut msg)?;
io_error!(websocket.send(Message::Binary(msg)), "Failed to write to ws connection: {}")?;
let websocketfd = websocket.get_ref().as_raw_fd();
let poll = WaitImpl::new(websocketfd, udpsocket.as_raw_fd(), 60 * 1000)?;
let mut buffer = [0; 65535];
for evt in poll {
match evt {
WaitResult::Socket => {
let msg = io_error!(websocket.read(), "Failed to read message on websocket {}: {}", peer)?;
match msg {
Message::Binary(data) => {
let dst = read_addr(Cursor::new(&data))?;
udpsocket.send_to(&data[18..], dst)?;
}
Message::Close(_) => return Ok(()),
_ => {}
}
}
WaitResult::Device => {
let (size, addr) = udpsocket.recv_from(&mut buffer)?;
let mut data = Vec::with_capacity(18 + size);
write_addr(addr, &mut data)?;
data.write_all(&buffer[..size])?;
io_error!(websocket.send(Message::Binary(data)), "Failed to write to {}: {}", peer)?;
}
WaitResult::Timeout => {
io_error!(websocket.send(Message::Ping(vec![])), "Failed to send ping: {}")?;
}
WaitResult::Error(err) => return Err(err),
}
}
Ok(())
}
pub fn run_proxy(listen: &str) -> Result<(), io::Error> {
let addr = parse_listen(listen, 8080);
let server = TcpListener::bind(addr)?;
info!("Listening on ws://{}", server.local_addr()?);
for stream in server.incoming() {
let stream = stream?;
let peer = stream.peer_addr()?;
spawn(move || {
if let Err(err) = serve_proxy_connection(stream) {
error!("Error on connection {}: {}", peer, err);
}
});
}
Ok(())
}
pub struct ProxyConnection {
addr: SocketAddr,
socket: WebSocket<MaybeTlsStream<TcpStream>>,
}
impl ProxyConnection {
fn read_message(&mut self) -> Result<Vec<u8>, io::Error> {
loop {
if let Message::Binary(data) = io_error!(self.socket.read(), "Failed to read from ws proxy: {}")? {
return Ok(data);
}
}
}
}
impl AsRawFd for ProxyConnection {
fn as_raw_fd(&self) -> RawFd {
match self.socket.get_ref() {
MaybeTlsStream::Plain(stream) => stream.as_raw_fd(),
_ => unimplemented!()
}
}
}
impl Socket for ProxyConnection {
fn listen(url: &str) -> Result<Self, io::Error> {
let parsed_url = io_error!(Url::parse(url), "Invalid URL {}: {}", url)?;
let (mut socket, _) = io_error!(connect(parsed_url), "Failed to connect to URL {}: {}", url)?;
socket.get_mut().set_nodelay(true)?;
let addr = "0.0.0.0:0".parse::<SocketAddr>().unwrap();
let mut con = ProxyConnection { addr, socket };
let addr_data = con.read_message()?;
con.addr = read_addr(Cursor::new(&addr_data))?;
Ok(con)
}
fn receive(&mut self, buffer: &mut MsgBuffer) -> Result<SocketAddr, io::Error> {
buffer.clear();
let data = self.read_message()?;
let addr = read_addr(Cursor::new(&data))?;
buffer.clone_from(&data[18..]);
Ok(addr)
}
fn send(&mut self, data: &[u8], addr: SocketAddr) -> Result<usize, io::Error> {
let mut msg = Vec::with_capacity(data.len() + 18);
write_addr(addr, &mut msg)?;
msg.write_all(data)?;
io_error!(self.socket.send(Message::Binary(msg)), "Failed to write to ws proxy: {}")?;
Ok(data.len())
}
fn address(&self) -> Result<SocketAddr, io::Error> {
Ok(self.addr)
}
fn create_port_forwarding(&self) -> Option<PortForwarding> {
None
}
}

View File

@ -45,7 +45,10 @@ vpncloud - Peer-to-peer VPN
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 \'\*' 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: **3210**]
otherwise the socket will only listen on the given IP.
Alternatively, a websocket proxy URL (starting with ws://) can be given
here. Please see the section *WEBSOCKET PROXY* for more info.
[default: **3210**]
*-c <addr>*, *--peer <addr>*, *--connect <addr>*::
Address of a peer to connect to. The address should be in the form
@ -62,31 +65,27 @@ vpncloud - Peer-to-peer VPN
Do not automatically claim the IP set on the virtual interface (on TUN
devices).
*-p <key>*, *--password <key>*::
*-p <password>*, *--password <password>*::
A password to encrypt the VPN data. This parameter must be set unless a
password is given in a config file or a private key is set.
See *SECURITY* for more info.
*--key <key>*, *--private-key <key>*::
A private key to use for encryption. The key must be given as base62 as
generated by *--genkey*. See *SECURITY* for more info.
generated by *genkey*. See *SECURITY* for more info.
*--public-key <key>*::
A public key matching the given private key. The key must be given as base62
as generated by *--genkey*. This argument is purely optional. See *SECURITY*
as generated by *genkey*. This argument is purely optional. See *SECURITY*
for more info.
*--trust <key>*, **--trusted-key <key>*::
A public key to trust. Any peer must have a key pair that is trusted by this
node, otherwise it will be rejected. The key must be given as base62 as
generated by *--genkey*. This argument can be given multiple times. If it is
generated by *genkey*. This argument can be given multiple times. If it is
not set, only the own public key will be trusted. See *SECURITY* for more
info.
*--genkey*::
Generate and print a random key pair and exit. The key pair is printed as
base62 and can be used as private-key, public-key and trusted-key options.
*--algo <method>*, *--algorithm <method>*::
Supported encryption algorithms ("plain", "aes128", "aes256", or "chacha20").
Nodes exchange the supported algorithms and select the one that is fastest on
@ -178,10 +177,12 @@ vpncloud - Peer-to-peer VPN
*--statsd-server <server>*::
If set, periodically send statistics on current traffic and some important
events to the given statsd server (host:port).
events to the given statsd server (host:port).
Please see *STATSD SUPPORT* for more info.
*--statsd-prefix <prefix>*::
Sets the prefix to use for all statsd entries. [default: **vpncloud**]
Please see *STATSD SUPPORT* for more info.
*--daemon*::
Spawn a background process instead of running the process in the foreground.
@ -196,6 +197,12 @@ vpncloud - Peer-to-peer VPN
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.
*--hook <script>*::
Call the given script on an event. If the script is in the format *event:script*,
it will only be called for the specified event type, otherwise it will be called
for all events. This parameter can be given multiple times.
Please see the section *HOOK SCRIPTS* for more info.
*-v*, *--verbose*::
Print debug information, including information for data being received and
sent.
@ -207,6 +214,41 @@ vpncloud - Peer-to-peer VPN
Display the help.
== SUBCOMMANDS
The following subcommands can be given to run some special action instead of
running a VpnCloud instance. Any parameters must be given after the subcommand
name (except for -v -q and -h). Only the listed parameters are accepted for the
subcommands.
*genkey*::
Generate and print a random key pair and exit. The key pair is printed as
base62 and can be used as private-key, public-key and trusted-key options.
See *SECURITY* for more info.
*-p <password>*, *--password <password>*:::
Derive the key pair from the given password instead of creating randomly.
*ws-proxy*::
Run a websocket proxy instead of the normal VpnCloud instance.
See *WEBSOCKET PROXY* for more info.
*-l <addr>*, *--listen <addr>*:::
Listen on the given TCP address (IP:PORT or PORT). [default: **3210**]
*migrate-config*::
Migrate an old config to the current config format.
*--config-file*:::
The path of the config file to convert.
*completion*::
Output shell completions for the VpnCloud command.
*--shell*:::
The shell type to create completions for. [default: **bash**]
== DESCRIPTION
*VpnCloud* is a peer-to-peer VPN over UDP. It creates a virtual network
@ -302,28 +344,28 @@ are optional and override the defaults. Please see the section *OPTIONS* for
detailed descriptions of the options.
*device*:: A key-value map with device settings
*type*:: Set the type of network. Same as *--type*
*name*:: Name of the virtual device. Same as *--device*
*path*:: Set the path of the base device. Same as *--device-path*
*fix-rp-filter*:: Fix the rp_filter settings on the host. Same as *--fix-rp-filter*
*type*::: Set the type of network. Same as *--type*
*name*::: Name of the virtual device. Same as *--device*
*path*::: Set the path of the base device. Same as *--device-path*
*fix-rp-filter*::: Fix the rp_filter settings on the host. Same as *--fix-rp-filter*
*ip*:: An IP address (plus optional prefix length) for the interface. Same as *--ip*
*ifup*:: A command to setup the network interface. Same as *--ifup*
*ifdown*:: A command to bring down the network interface. Same as *--ifdown*
*crypto*:: A key-value map with crypto settings
*algorithms*:: The encryption algorithms to support. See *--algorithm*
*password*:: The password to use for encryption. Same as *--password*
*private-key*:: The private key to use. Same as *--private-key*
*public-key*:: The public key to use. Same as *--public-key*
*trusted-keys*:: Other public keys to trust. See *--trusted-key*
*algorithms*::: The encryption algorithms to support. See *--algorithm*
*password*::: The password to use for encryption. Same as *--password*
*private-key*::: The private key to use. Same as *--private-key*
*public-key*::: The public key to use. Same as *--public-key*
*trusted-keys*::: Other public keys to trust. See *--trusted-key*
*listen*:: The address on which to listen for data. Same as *--listen*
*peers*:: A list of addresses to connect to. See *--connect*
*peer_timeout*:: Peer timeout in seconds. Same as *--peer-timeout*
*keepalive*:: Periodically send message to keep connections alive. Same as *--keepalive*
*beacon*:: A key-value map with beacon settings
*store*:: Path or command to store beacons. Same as *--beacon-store*
*load*:: Path or command to load beacons. Same as *--beacon-load*
*interval*:: Interval for loading and storing beacons in seconds. Same as *--beacon-interval*
*password*:: Password to encrypt the beacon with. Same as *--beacon-password*
*store*::: Path or command to store beacons. Same as *--beacon-store*
*load*::: Path or command to load beacons. Same as *--beacon-load*
*interval*::: Interval for loading and storing beacons in seconds. Same as *--beacon-interval*
*password*::: Password to encrypt the beacon with. Same as *--beacon-password*
*mode*:: The mode of the VPN. Same as *--mode*
*switch_timeout*:: Switch table entry timeout in seconds. Same as *--switch-timeout*
*claims*:: A list of local subnets to claim. See *--claim*
@ -334,8 +376,10 @@ detailed descriptions of the options.
*pid_file*:: The path of the pid file to create. Same as *--pid-file*
*stats_file*:: The path of the statistics file. Same as *--stats-file*
*statsd*:: A key-value map with statsd settings
*server*:: Server to report statistics to. Same as *--statsd-server*
*prefix*:: Prefix to use when reporting to statsd. Same as *--statsd-prefix*
*server*::: Server to report statistics to. Same as *--statsd-server*
*prefix*::: Prefix to use when reporting to statsd. Same as *--statsd-prefix*
*hook*:: A hook script to be called for every event type. See *HOOK SCRIPTS* for info.
*hooks*:: A map of event type to script for scripts that only fire for one event type. See *HOOK SCRIPTS* for info.
=== Example
@ -366,7 +410,7 @@ VpnCloud uses strong cryptography based on modern cryptographic primitives.
Before exchanging any payload data with peers a secure connection is
initialized based on key pairs. Each node has a key pair consisting of a
private and a public key (*--private-key* and *--public-key*). Those key pairs
can be generated via *--genkey*.
can be generated via *genkey*.
To allow connections, nodes need to list the public keys of all other nodes as
trusted keys (*--trusted-key*). To simplify the key exchange, key pairs can be
derived from passwords (*--password*). If no trusted keys are configured, nodes
@ -461,6 +505,90 @@ All keys are prefixed by a common prefix. The prefix defaults to *vpncloud* but
can be changed via **--statsd-prefix** or the config option **statsd_prefix**.
== WEBSOCKET PROXY
The websocket proxy mode replaces the local UDP port by a websocket proxy to allow
connectivity even in very restricted environments.
This means that instead of listening on a local port for incoming messages and
sending outgoing messages via this port, all UDP traffic will be forwarded to and
received from a remote proxy via the websocket protocol. This proxy opens a UDP
port for each VpnCloud instance that connects to it. The instance can use this port
remotely just like it would use a real local UDP port.
The proxy is transparent, it does not manipulate or even decrypt the messages it
forwards. Trust relations are still created between VpnCloud instances, not between
an instance and the proxy. The proxy only ever sees encrypted messages. Therefore,
the connection to it uses plain HTTP.
A websocket proxy can be stared by using the *ws-proxy* subcommand. A custom port
can be set using the *--listen* parameter. (Note that this port never conflicts
with a VpnCloud port on the same machine since VpnCloud uses UDP and the proxy uses
TCP.)
A VpnCloud instance can use a websocket proxy instead of opening a local port by
specifying the websocket proxy via its *--listen* parameter
(e.g. *--listen ws://example.com:3210*). Note that the websocket URL must start with
*ws:\/\/*, not *http:\/\/*.
== HOOK SCRIPTS
VpnCloud supports calling hook scripts on certain events. The scripts can either be
configured on the command line or in the config file. Hook scripts can either be
configured per event type or globally.
When an event occurs, the specified hook script is executed using
the current permissions of the user that started the instance. Note that this means
that if VpnCloud is configured to drop permissions, only the events *device_setup*
and *device_configured* will be executed using root permissions.
Hook scripts are executed using *sh -c*, so either binaries, shell scripts and even
shell commands can be used. The script will be executed in parallel to the VpnCloud
instance. Its output will be printed to the stdout of VpnCloud and the return code
is ignored.
The hook script will receive information on the event using environment variables.
The variable *EVENT* will contain the name of the event. Other variables depend on
the event type.
The following event types
*peer_connecting*::
A new peer connection is in the process of being established. The variable
*PEER* contains the address of the peer but no other information is known at
that point in time.
Variables: *IFNAME*, *PEER*
*peer_connected*::
A new peer successfully connected to this instance. Besides the peer address,
also a list of claims (*CLAIMS*, space separated) and the node id of the new
peer (*NODE_ID*) are given to the script.
Variables: *IFNAME*, *PEER*, *CLAIMS*, *NODE_ID*
*peer_disconnected*::
A peer connection has been closed. If the peer has been fully connected, the
node id is given (*NODE_ID*).
Variables: *IFNAME*, *PEER*, (*NODE_ID*)
*device_setup*::
This event is fired when the virtual device has been created but not yet
configured.
Variables: *IFNAME*
*device_configured*::
This event is fired when the virtual device is fully configured.
Variables: *IFNAME*
*vpn_started*::
This event is fired when the VPN is ready to be used.
Variables: *IFNAME*
*vpn_shutdown*::
This event is fired when the VPN s shutting down.
Variables: *IFNAME*
== DEVICE SETUP
The device is setup using the following steps:
@ -486,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)