Compare commits

...

144 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
89 changed files with 4465 additions and 3632 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" }

View File

@ -1,6 +0,0 @@
# See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.148.1/containers/rust/.devcontainer/base.Dockerfile
FROM mcr.microsoft.com/vscode/devcontainers/rust:0-1
RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
&& apt-get -y install --no-install-recommends asciidoctor

View File

@ -1,35 +0,0 @@
{
"name": "Rust",
"build": {
"dockerfile": "Dockerfile"
},
"runArgs": [ "--cap-add=SYS_PTRACE", "--security-opt", "seccomp=unconfined" ],
// Set *default* container specific settings.json values on container create.
"settings": {
"terminal.integrated.shell.linux": "/bin/bash",
"lldb.executable": "/usr/bin/lldb",
// VS Code don't watch files under ./target
"files.watcherExclude": {
"**/target/**": true
}
},
// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"rust-lang.rust",
"bungcip.better-toml",
"vadimcn.vscode-lldb",
"mutantdino.resourcemonitor",
"asciidoctor.asciidoctor-vscode"
],
// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],
// Use 'postCreateCommand' to run commands after the container is created.
// "postCreateCommand": "rustc --version",
// Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
"remoteUser": "vscode"
}

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

@ -2,6 +2,11 @@ FROM centos:7
RUN yum groupinstall -y 'Development Tools'
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.49.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.49.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,34 @@
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

1185
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,52 +1,65 @@
[package]
name = "vpncloud"
version = "2.1.0"
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.22"
chrono = { version = "0.4", features = ["std", "clock"], default_features = false}
structopt = "0.3"
serde = { version = "1.0", features = ["derive"] }
serde_yaml = "0.8"
serde_yaml = "0.9"
log = { version = "0.4", features = ["std"] }
signal = "0.7"
libc = "0.2"
rand = "0.8"
fnv = "1"
yaml-rust = "0.4"
igd = { version = "0.12", optional = true }
daemonize = "0.4"
ring = "0.16"
daemonize = "0.5"
ring = "0.17"
privdrop = "0.5"
byteorder = "1.4"
thiserror = "1.0"
smallvec = "1.6"
tungstenite = { version = "0.12", optional = true, default-features = false }
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.3", features = ["html_reports"] }
criterion = { version = "0.5", features = ["html_reports"] }
iai = "0.1"
[features]
default = ["nat", "websocket"]
default = ["nat", "websocket", "wizard"]
nat = ["igd"]
websocket = ["tungstenite", "url"]
wizard = ["dialoguer"]
installer = []
[[bench]]
name = "bench"
name = "criterion"
harness = false
[[bench]]
name = "valgrind"
harness = false
[profile.release]
lto = true
strip = true
[profile.dev]
lto = false
@ -56,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"
@ -69,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

@ -19,7 +19,7 @@ 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
@ -35,6 +35,7 @@ somewhat stable state. VpnCloud features the following functionality:
* 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
@ -61,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,29 @@
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
@ -9,7 +35,7 @@ vpncloud (2.1.0) stable; urgency=medium
* [fixed] Added missing peer address propagation
* [fixed] Fixed problem with peer addresses without port
-- Dennis Schwerdel <schwerdel@googlemail.com> Sat, 06 Feb 2020 13:13:00 +0100
-- Dennis Schwerdel <schwerdel@googlemail.com> Sat, 06 Feb 2021 13:13:00 +0100
vpncloud (2.0.1) stable; urgency=medium

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

View File

@ -10,31 +10,17 @@ use ring::aead;
use std::str::FromStr;
use std::net::{SocketAddr, Ipv4Addr, SocketAddrV4, UdpSocket};
mod util {
include!("../src/util.rs");
}
mod error {
include!("../src/error.rs");
}
mod payload {
include!("../src/payload.rs");
}
mod types {
include!("../src/types.rs");
}
mod table {
include!("../src/table.rs");
}
mod crypto_core {
include!("../src/crypto/core.rs");
}
include!(".code.rs");
pub use error::Error;
use util::{MockTimeSource, MsgBuffer};
use types::{Address, Range};
use table::{ClaimTable};
use table::ClaimTable;
use device::Type;
use config::Config;
use payload::{Packet, Frame, Protocol};
use crypto_core::{create_dummy_pair, EXTRA_LEN};
use crypto::core::{create_dummy_pair, EXTRA_LEN};
use tests::common::{TunSimulator, TapSimulator};
fn udp_send(c: &mut Criterion) {
let sock = UdpSocket::bind("127.0.0.1:0").unwrap();
@ -43,7 +29,7 @@ fn udp_send(c: &mut Criterion) {
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());
b.iter(|| sock.send_to(&data, addr).unwrap());
});
g.finish();
}
@ -145,5 +131,74 @@ fn crypto_aes256(c: &mut Criterion) {
crypto_bench(c, &aead::AES_256_GCM)
}
criterion_group!(benches, udp_send, decode_ipv4, decode_ipv6, decode_ethernet, decode_ethernet_with_vlan, lookup_cold, lookup_warm, crypto_chacha20, crypto_aes128, crypto_aes256);
fn full_communication_tun_router(c: &mut Criterion) {
log::set_max_level(log::LevelFilter::Error);
let config1 = Config {
device_type: Type::Tun,
auto_claim: false,
claims: vec!["1.1.1.1/32".to_string()],
..Config::default()
};
let config2 = Config {
device_type: Type::Tun,
auto_claim: false,
claims: vec!["2.2.2.2/32".to_string()],
..Config::default()
};
let mut sim = TunSimulator::new();
let node1 = sim.add_node(false, &config1);
let node2 = sim.add_node(false, &config2);
sim.connect(node1, node2);
sim.simulate_all_messages();
assert!(sim.is_connected(node1, node2));
assert!(sim.is_connected(node2, node1));
let mut payload = vec![0x40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2];
payload.append(&mut vec![0; 1400]);
let mut g = c.benchmark_group("full_communication");
g.throughput(Throughput::Bytes(2*1400));
g.bench_function("tun_router", |b| {
b.iter(|| {
sim.put_payload(node1, payload.clone());
sim.simulate_all_messages();
assert_eq!(Some(&payload), sim.pop_payload(node2).as_ref());
});
});
g.finish()
}
fn full_communication_tap_switch(c: &mut Criterion) {
log::set_max_level(log::LevelFilter::Error);
let config = Config { device_type: Type::Tap, ..Config::default() };
let mut sim = TapSimulator::new();
let node1 = sim.add_node(false, &config);
let node2 = sim.add_node(false, &config);
sim.connect(node1, node2);
sim.simulate_all_messages();
assert!(sim.is_connected(node1, node2));
assert!(sim.is_connected(node2, node1));
let mut payload = vec![2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5];
payload.append(&mut vec![0; 1400]);
let mut g = c.benchmark_group("full_communication");
g.throughput(Throughput::Bytes(2*1400));
g.bench_function("tap_switch", |b| {
b.iter(|| {
sim.put_payload(node1, payload.clone());
sim.simulate_all_messages();
assert_eq!(Some(&payload), sim.pop_payload(node2).as_ref());
});
});
g.finish()
}
criterion_group!(benches,
udp_send,
decode_ipv4, decode_ipv6, decode_ethernet, decode_ethernet_with_vlan,
lookup_cold, lookup_warm,
crypto_chacha20, crypto_aes128, crypto_aes256,
full_communication_tun_router, full_communication_tap_switch
);
criterion_main!(benches);

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.49.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 -v 2.0.10
RUN useradd -ms /bin/bash user
USER user
WORKDIR /home/user
ENV RUST=1.49.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.1"
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.1"
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')

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,26 +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![
SocketAddr::from_str("1.2.3.4:5678").unwrap(),
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 peers = vec![
SocketAddr::from_str("1.2.3.4:5678").unwrap(),
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));
}
@ -343,10 +338,7 @@ fn encode() {
fn decode() {
MockTimeSource::set_time(2000 * 3600);
let ser = BeaconSerializer::<MockTimeSource>::new(b"mysecretkey");
let mut peers = vec![
SocketAddr::from_str("1.2.3.4:5678").unwrap(),
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!(
@ -359,10 +351,7 @@ fn decode() {
fn decode_split() {
MockTimeSource::set_time(2000 * 3600);
let ser = BeaconSerializer::<MockTimeSource>::new(b"mysecretkey");
let peers = vec![
SocketAddr::from_str("1.2.3.4:5678").unwrap(),
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))
@ -377,10 +366,7 @@ fn decode_split() {
fn decode_offset() {
MockTimeSource::set_time(2000 * 3600);
let ser = BeaconSerializer::<MockTimeSource>::new(b"mysecretkey");
let peers = vec![
SocketAddr::from_str("1.2.3.4:5678").unwrap(),
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))
@ -391,10 +377,7 @@ fn decode_offset() {
fn decode_multiple() {
MockTimeSource::set_time(2000 * 3600);
let ser = BeaconSerializer::<MockTimeSource>::new(b"mysecretkey");
let peers = vec![
SocketAddr::from_str("1.2.3.4:5678").unwrap(),
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))
@ -438,15 +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 peers = vec![
SocketAddr::from_str("1.2.3.4:5678").unwrap(),
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));
@ -456,10 +435,7 @@ fn encode_decode() {
fn encode_decode_file() {
MockTimeSource::set_time(2000 * 3600);
let ser = BeaconSerializer::<MockTimeSource>::new(b"mysecretkey");
let peers = vec![
SocketAddr::from_str("1.2.3.4:5678").unwrap(),
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);
@ -471,10 +447,7 @@ fn encode_decode_file() {
fn encode_decode_cmd() {
MockTimeSource::set_time(2000 * 3600);
let ser = BeaconSerializer::<MockTimeSource>::new(b"mysecretkey");
let peers = vec![
SocketAddr::from_str("1.2.3.4:5678").unwrap(),
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;
@ -27,16 +27,16 @@ use crate::{
error::Error,
messages::{
AddrList, NodeInfo, PeerInfo, MESSAGE_TYPE_CLOSE, MESSAGE_TYPE_DATA, MESSAGE_TYPE_KEEPALIVE,
MESSAGE_TYPE_NODE_INFO
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, bytes_to_hex, 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>;
@ -54,7 +54,7 @@ struct PeerData {
timeout: Time,
peer_timeout: u16,
node_id: NodeId,
crypto: PeerCrypto<NodeInfo>
crypto: PeerCrypto<NodeInfo>,
}
#[derive(Clone)]
@ -64,10 +64,9 @@ pub struct ReconnectEntry {
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,
@ -95,22 +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, socket: S, device: D, port_forwarding: Option<PortForwarding>, stats_file: Option<File>) -> Self {
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 => (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 {
@ -126,7 +125,7 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
Err(Error::DeviceIo(_, e)) if e.kind() == io::ErrorKind::AddrNotAvailable => {
info!("No address set on interface.")
}
Err(e) => error!("{}", e)
Err(e) => error!("{}", e),
}
}
let now = TS::now();
@ -161,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
@ -191,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(())
@ -205,7 +204,7 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
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)),
}
}
@ -215,7 +214,7 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
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)
@ -223,7 +222,14 @@ 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());
@ -258,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,
})
}
@ -277,14 +283,14 @@ 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
true,
);
}
// Send a message to each resolved address
@ -310,7 +316,7 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
peers,
claims: self.claims.clone(),
peer_timeout: Some(self.peer_timeout_publish),
addrs: self.own_addresses.clone()
addrs: self.own_addresses.clone(),
}
}
@ -320,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();
@ -340,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]>>() {
@ -349,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 {
@ -366,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
@ -385,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;
@ -420,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);
}
@ -438,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");
@ -451,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()?;
@ -473,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(())
}
@ -487,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))?;
}
}
@ -502,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 {
@ -595,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);
@ -648,17 +652,20 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
("CLAIMS", info.claims.iter().map(|r| format!("{:?}", r)).collect::<Vec<String>>().join(" ")),
("NODE_ID", bytes_to_hex(&info.node_id)),
],
true
true,
);
if let Some(init) = self.pending_inits.remove(&addr) {
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.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));
@ -677,7 +684,7 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
("IFNAME", self.device.ifname().to_owned()),
("NODE_ID", bytes_to_hex(&peer.node_id)),
],
true
true,
);
}
}
@ -686,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;
}
}
}
@ -707,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);
@ -729,7 +752,7 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
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
@ -739,7 +762,7 @@ 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 {
@ -756,7 +779,7 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
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))?
@ -772,7 +795,7 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
_ => {
// COLD PATH
self.traffic.count_invalid_protocol(data.len());
return Err(Error::Message("Unknown message type"))
return Err(Error::Message("Unknown message type"));
}
}
}
@ -824,14 +847,14 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
("PEER", format!("{:?}", addr_nice(src))),
("IFNAME", self.device.ifname().to_owned()),
],
true
true,
);
self.pending_inits.insert(src, init);
Ok(res)
}
Err(err) => {
self.traffic.count_invalid_protocol(data.len());
return Err(err)
return Err(err);
}
}
}
@ -842,14 +865,14 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
// 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) => {
// HOT PATH
self.handle_message(src, val, data)
},
}
Err(err) => {
// COLD PATH
self.traffic.count_invalid_protocol(data.len());
@ -877,7 +900,7 @@ impl<D: Device, P: Protocol, S: Socket, TS: TimeSource> GenericCloud<D, P, S, TS
self.config.call_hook(
"peer_disconnected",
vec![("PEER", format!("{:?}", addr_nice(src))), ("IFNAME", self.device.ifname().to_owned())],
true
true,
);
}
Err(e @ Error::CryptoInit(_)) => {
@ -910,7 +933,10 @@ 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.as_raw_fd(), self.device.as_raw_fd(), 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);
@ -927,13 +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)
@ -957,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,23 +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, util::run_cmd};
use super::{device::Type, types::Mode, util::run_cmd, util::Duration};
pub use crate::crypto::Config as CryptoConfig;
use std::{
cmp::max,
collections::HashMap,
ffi::OsStr,
process,
thread
};
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;
#[derive(Deserialize, Debug, PartialEq, Clone)]
pub struct Config {
pub device_type: Type,
@ -26,6 +19,7 @@ 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>,
@ -52,7 +46,7 @@ pub struct Config {
pub user: Option<String>,
pub group: Option<String>,
pub hook: Option<String>,
pub hooks: HashMap<String, String>
pub hooks: HashMap<String, String>,
}
impl Default for Config {
@ -63,6 +57,7 @@ impl Default for Config {
device_path: None,
fix_rp_filter: false,
ip: None,
advertise_addresses: vec![],
ifup: None,
ifdown: None,
crypto: CryptoConfig::default(),
@ -87,7 +82,7 @@ impl Default for Config {
user: None,
group: None,
hook: None,
hooks: HashMap::new()
hooks: HashMap::new(),
}
}
}
@ -112,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);
}
@ -219,6 +217,7 @@ 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);
}
@ -295,7 +294,7 @@ impl Config {
if s.contains(':') {
let pos = s.find(':').unwrap();
let name = &s[..pos];
let hook = &s[pos+1..];
let hook = &s[pos + 1..];
self.hooks.insert(name.to_string(), hook.to_string());
} else {
self.hook = Some(s);
@ -303,6 +302,44 @@ impl Config {
}
}
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,
@ -311,17 +348,17 @@ impl Config {
}
pub fn call_hook(
&self, event: &'static str, envs: impl IntoIterator<Item = (&'static str, impl AsRef<OsStr>)>, detach: bool
&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(ref s) = self.hooks.get(event) {
if let Some(s) = self.hooks.get(event) {
script = Some(s);
}
if script.is_none() {
return
return;
}
let script = script.unwrap();
let mut cmd = process::Command::new("sh");
@ -437,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>,
@ -508,8 +549,8 @@ pub enum Command {
#[structopt(alias = "wsproxy")]
WsProxy {
/// Websocket listen address IP:PORT
#[structopt(long, short, default_value="3210")]
listen: String
#[structopt(long, short, default_value = "3210")]
listen: String,
},
/// Migrate an old config file
@ -523,9 +564,25 @@ pub enum Command {
/// Generate shell completions
Completion {
/// Shell to create completions for
#[structopt(long, default_value="bash")]
shell: Shell
}
#[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)]
@ -560,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>,
@ -581,7 +639,7 @@ pub struct ConfigFile {
pub user: Option<String>,
pub group: Option<String>,
pub hook: Option<String>,
pub hooks: HashMap<String, String>
pub hooks: HashMap<String, String>,
}
#[test]
@ -592,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:
@ -627,6 +688,7 @@ statsd:
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(),
@ -660,43 +722,8 @@ statsd:
}
#[test]
fn default_config_as_default() {
let mut default_config = Config {
device_type: Type::Tun,
device_name: "".to_string(),
device_path: None,
fix_rp_filter: false,
ip: None,
ifup: None,
ifdown: None,
crypto: CryptoConfig::default(),
listen: "[::]:3210".to_string(),
peers: vec![],
peer_timeout: 0,
keepalive: None,
beacon_store: None,
beacon_load: None,
beacon_interval: 0,
beacon_password: None,
mode: Mode::Hub,
switch_timeout: 0,
claims: vec![],
auto_claim: true,
port_forwarding: true,
daemonize: false,
pid_file: None,
stats_file: None,
statsd_server: None,
statsd_prefix: None,
user: None,
group: None,
hook: None,
hooks: HashMap::new()
};
let default_config_file =
serde_yaml::from_str::<ConfigFile>(include_str!("../assets/example.net.disabled")).unwrap();
default_config.merge_file(default_config_file);
assert_eq!(default_config, Config::default());
fn parse_example_config() {
serde_yaml::from_str::<ConfigFile>(include_str!("../assets/example.net.disabled")).unwrap();
}
#[test]
@ -710,6 +737,7 @@ fn config_merge() {
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(),
@ -737,35 +765,39 @@ fn config_merge() {
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,
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()
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()),
@ -794,40 +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".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()
});
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,3 +1,7 @@
// VpnCloud - Peer-to-Peer VPN
// Copyright (C) 2015-2021 Dennis Schwerdel
// This software is licensed under GPL-3 or newer (see LICENSE.md)
// This module implements a crypto core for encrypting and decrypting message streams
//
// The crypto core only encrypts and decrypts messages, using given keys. Negotiating and rotating the keys is out of
@ -40,23 +44,21 @@
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>());

View File

@ -1,3 +1,7 @@
// VpnCloud - Peer-to-Peer VPN
// Copyright (C) 2015-2021 Dennis Schwerdel
// This software is licensed under GPL-3 or newer (see LICENSE.md)
// This module implements a 3-way handshake to initialize an authenticated and encrypted connection.
//
// The handshake assumes that each node has a asymmetric Curve 25519 key pair as well as a list of trusted public keys
@ -50,29 +54,27 @@
// 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,
@ -393,15 +392,14 @@ pub struct InitState<P: Payload> {
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();
@ -421,7 +419,7 @@ impl<P: Payload> InitState<P> {
selected_algorithm: None,
algorithms,
failed_retries: 0,
close_time: 60
close_time: 60,
}
}
@ -461,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()
}
@ -507,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);
}
@ -547,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.
@ -581,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 {
@ -593,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;
@ -663,7 +655,6 @@ impl<P: Payload> InitState<P> {
}
}
#[cfg(test)]
mod tests {
use super::*;
@ -671,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())
}
@ -695,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);
@ -715,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!(),
}
}
@ -746,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!(),
}
}
@ -777,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();
@ -785,7 +776,7 @@ mod tests {
assert_eq!(receiver.stage(), CLOSING);
match result {
InitResult::Success { .. } => assert!(out.is_empty()),
InitResult::Continue => unreachable!()
InitResult::Continue => unreachable!(),
}
}
@ -834,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;
@ -844,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();
@ -858,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
@ -929,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,504 +1,11 @@
// VpnCloud - Peer-to-Peer VPN
// Copyright (C) 2015-2021 Dennis Schwerdel
// This software is licensed under GPL-3 or newer (see LICENSE.md)
mod common;
mod core;
mod init;
mod rotate;
pub use self::core::{EXTRA_LEN, TAG_LEN};
use self::{
core::{test_speed, CryptoCore},
init::{InitResult, InitState, CLOSING},
rotate::RotationState
};
use crate::{
error::Error,
types::NodeId,
util::{from_base62, to_base62, MsgBuffer}
};
use ring::{
aead::{self, Algorithm, LessSafeKey, UnboundKey},
agreement::{EphemeralPrivateKey, UnparsedPublicKey},
pbkdf2,
rand::{SecureRandom, SystemRandom},
signature::{Ed25519KeyPair, KeyPair, ED25519_PUBLIC_KEY_LEN}
};
use smallvec::{smallvec, SmallVec};
use std::{fmt::Debug, io::Read, num::NonZeroU32, sync::Arc, time::Duration};
use thiserror::Error;
const SALT: &[u8; 32] = b"vpncloudVPNCLOUDvpncl0udVpnCloud";
const INIT_MESSAGE_FIRST_BYTE: u8 = 0xff;
const MESSAGE_TYPE_ROTATION: u8 = 0x10;
pub type Ed25519PublicKey = [u8; ED25519_PUBLIC_KEY_LEN];
pub type EcdhPublicKey = UnparsedPublicKey<SmallVec<[u8; 96]>>;
pub type EcdhPrivateKey = EphemeralPrivateKey;
pub type Key = SmallVec<[u8; 32]>;
const DEFAULT_ALGORITHMS: [&str; 3] = ["AES128", "AES256", "CHACHA20"];
#[cfg(test)]
const SPEED_TEST_TIME: f32 = 0.02;
#[cfg(not(test))]
const SPEED_TEST_TIME: f32 = 0.1;
const ROTATE_INTERVAL: usize = 120;
pub trait Payload: Debug + PartialEq + Sized {
fn write_to(&self, buffer: &mut MsgBuffer);
fn read_from<R: Read>(r: R) -> Result<Self, Error>;
}
#[derive(Clone)]
pub struct Algorithms {
pub algorithm_speeds: SmallVec<[(&'static Algorithm, f32); 3]>,
pub allow_unencrypted: bool
}
#[derive(Debug, Default, Deserialize, Serialize, Clone, PartialEq)]
#[serde(rename_all = "kebab-case", deny_unknown_fields, default)]
pub struct Config {
pub password: Option<String>,
pub private_key: Option<String>,
pub public_key: Option<String>,
pub trusted_keys: Vec<String>,
pub algorithms: Vec<String>
}
pub struct Crypto {
node_id: NodeId,
key_pair: Arc<Ed25519KeyPair>,
trusted_keys: Arc<[Ed25519PublicKey]>,
algorithms: Algorithms
}
impl Crypto {
pub fn new(node_id: NodeId, config: &Config) -> Result<Self, Error> {
let key_pair = if let Some(priv_key) = &config.private_key {
if let Some(pub_key) = &config.public_key {
Self::parse_keypair(priv_key, pub_key)?
} else {
Self::parse_private_key(priv_key)?
}
} else if let Some(password) = &config.password {
Self::keypair_from_password(password)
} else {
return Err(Error::InvalidConfig("Either private_key or password must be set"))
};
let mut trusted_keys = vec![];
for tn in &config.trusted_keys {
trusted_keys.push(Self::parse_public_key(tn)?);
}
if trusted_keys.is_empty() {
info!("Trusted keys not set, trusting only own public key");
let mut key = [0; ED25519_PUBLIC_KEY_LEN];
key.clone_from_slice(key_pair.public_key().as_ref());
trusted_keys.push(key);
}
let mut algos = Algorithms { algorithm_speeds: smallvec![], allow_unencrypted: false };
let algorithms = config.algorithms.iter().map(|a| a as &str).collect::<Vec<_>>();
let allowed = if algorithms.is_empty() { &DEFAULT_ALGORITHMS } else { &algorithms as &[&str] };
let duration = Duration::from_secs_f32(SPEED_TEST_TIME);
let mut speeds = Vec::new();
for name in allowed {
let algo = match &name.to_uppercase() as &str {
"UNENCRYPTED" | "NONE" | "PLAIN" => {
algos.allow_unencrypted = true;
warn!("Crypto settings allow unencrypted connections");
continue
}
"AES128" | "AES128_GCM" | "AES_128" | "AES_128_GCM" => &aead::AES_128_GCM,
"AES256" | "AES256_GCM" | "AES_256" | "AES_256_GCM" => &aead::AES_256_GCM,
"CHACHA" | "CHACHA20" | "CHACHA20_POLY1305" => &aead::CHACHA20_POLY1305,
_ => return Err(Error::InvalidConfig("Unknown crypto method"))
};
let speed = test_speed(algo, &duration);
algos.algorithm_speeds.push((algo, speed as f32));
speeds.push((name, speed as f32));
}
if !speeds.is_empty() {
info!(
"Crypto speeds: {}",
speeds.into_iter().map(|(a, s)| format!("{}: {:.1} MiB/s", a, s)).collect::<Vec<_>>().join(", ")
);
}
Ok(Self {
node_id,
key_pair: Arc::new(key_pair),
trusted_keys: trusted_keys.into_boxed_slice().into(),
algorithms: algos
})
}
pub fn generate_keypair(password: Option<&str>) -> (String, String) {
let mut bytes = [0; 32];
match password {
None => {
let rng = SystemRandom::new();
rng.fill(&mut bytes).unwrap();
}
Some(password) => {
pbkdf2::derive(
pbkdf2::PBKDF2_HMAC_SHA256,
NonZeroU32::new(4096).unwrap(),
SALT,
password.as_bytes(),
&mut bytes
);
}
}
let keypair = Ed25519KeyPair::from_seed_unchecked(&bytes).unwrap();
let privkey = to_base62(&bytes);
let pubkey = to_base62(keypair.public_key().as_ref());
(privkey, pubkey)
}
fn keypair_from_password(password: &str) -> Ed25519KeyPair {
let mut key = [0; 32];
pbkdf2::derive(pbkdf2::PBKDF2_HMAC_SHA256, NonZeroU32::new(4096).unwrap(), SALT, password.as_bytes(), &mut key);
Ed25519KeyPair::from_seed_unchecked(&key).unwrap()
}
fn parse_keypair(privkey: &str, pubkey: &str) -> Result<Ed25519KeyPair, Error> {
let privkey = from_base62(privkey).map_err(|_| Error::InvalidConfig("Failed to parse private key"))?;
let pubkey = from_base62(pubkey).map_err(|_| Error::InvalidConfig("Failed to parse public key"))?;
let keypair = Ed25519KeyPair::from_seed_and_public_key(&privkey, &pubkey)
.map_err(|_| Error::InvalidConfig("Keys rejected by crypto library"))?;
Ok(keypair)
}
fn parse_private_key(privkey: &str) -> Result<Ed25519KeyPair, Error> {
let privkey = from_base62(privkey).map_err(|_| Error::InvalidConfig("Failed to parse private key"))?;
let keypair = Ed25519KeyPair::from_seed_unchecked(&privkey)
.map_err(|_| Error::InvalidConfig("Key rejected by crypto library"))?;
Ok(keypair)
}
fn parse_public_key(pubkey: &str) -> Result<Ed25519PublicKey, Error> {
let pubkey = from_base62(pubkey).map_err(|_| Error::InvalidConfig("Failed to parse public key"))?;
if pubkey.len() != ED25519_PUBLIC_KEY_LEN {
return Err(Error::InvalidConfig("Failed to parse public key"))
}
let mut result = [0; ED25519_PUBLIC_KEY_LEN];
result.clone_from_slice(&pubkey);
Ok(result)
}
pub fn peer_instance<P: Payload>(&self, payload: P) -> PeerCrypto<P> {
PeerCrypto::new(
self.node_id,
payload,
self.key_pair.clone(),
self.trusted_keys.clone(),
self.algorithms.clone()
)
}
}
#[derive(Debug, PartialEq)]
pub enum MessageResult<P: Payload> {
Message(u8),
Initialized(P),
InitializedWithReply(P),
Reply,
None
}
pub struct PeerCrypto<P: Payload> {
#[allow(dead_code)]
node_id: NodeId,
init: Option<InitState<P>>,
rotation: Option<RotationState>,
unencrypted: bool,
core: Option<CryptoCore>,
rotate_counter: usize
}
impl<P: Payload> PeerCrypto<P> {
pub fn new(
node_id: NodeId, init_payload: P, key_pair: Arc<Ed25519KeyPair>, trusted_keys: Arc<[Ed25519PublicKey]>,
algorithms: Algorithms
) -> Self
{
Self {
node_id,
init: Some(InitState::new(node_id, init_payload, key_pair, trusted_keys, algorithms)),
rotation: None,
unencrypted: false,
core: None,
rotate_counter: 0
}
}
fn get_init(&mut self) -> Result<&mut InitState<P>, Error> {
if let Some(init) = &mut self.init {
Ok(init)
} else {
Err(Error::InvalidCryptoState("Initialization already finished"))
}
}
fn get_core(&mut self) -> Result<&mut CryptoCore, Error> {
if let Some(core) = &mut self.core {
Ok(core)
} else {
Err(Error::InvalidCryptoState("Crypto core not ready yet"))
}
}
fn get_rotation(&mut self) -> Result<&mut RotationState, Error> {
if let Some(rotation) = &mut self.rotation {
Ok(rotation)
} else {
Err(Error::InvalidCryptoState("Key rotation not initialized"))
}
}
pub fn initialize(&mut self, out: &mut MsgBuffer) -> Result<(), Error> {
let init = self.get_init()?;
if init.stage() != init::STAGE_PING {
Err(Error::InvalidCryptoState("Initialization already ongoing"))
} else {
init.send_ping(out);
out.prepend_byte(INIT_MESSAGE_FIRST_BYTE);
Ok(())
}
}
pub fn has_init(&self) -> bool {
self.init.is_some()
}
pub fn is_ready(&self) -> bool {
self.core.is_some()
}
pub fn algorithm_name(&self) -> &'static str {
if let Some(ref core) = self.core {
let algo = core.algorithm();
if algo == &aead::CHACHA20_POLY1305 {
"CHACHA20"
} else if algo == &aead::AES_128_GCM {
"AES128"
} else if algo == &aead::AES_256_GCM {
"AES256"
} else {
unreachable!()
}
} else {
"PLAIN"
}
}
fn handle_init_message(&mut self, buffer: &mut MsgBuffer) -> Result<MessageResult<P>, Error> {
let result = self.get_init()?.handle_init(buffer)?;
if !buffer.is_empty() {
buffer.prepend_byte(INIT_MESSAGE_FIRST_BYTE);
}
match result {
InitResult::Continue => Ok(MessageResult::Reply),
InitResult::Success { peer_payload, is_initiator } => {
self.core = self.get_init()?.take_core();
if self.core.is_none() {
self.unencrypted = true;
}
if self.get_init()?.stage() == init::CLOSING {
self.init = None
}
if self.core.is_some() {
self.rotation = Some(RotationState::new(!is_initiator, buffer));
}
if !is_initiator {
if self.unencrypted {
return Ok(MessageResult::Initialized(peer_payload))
}
assert!(!buffer.is_empty());
buffer.prepend_byte(MESSAGE_TYPE_ROTATION);
self.encrypt_message(buffer)?;
}
Ok(MessageResult::InitializedWithReply(peer_payload))
}
}
}
fn handle_rotate_message(&mut self, data: &[u8]) -> Result<(), Error> {
if self.unencrypted {
return Ok(())
}
if let Some(rot) = self.get_rotation()?.handle_message(data)? {
let core = self.get_core()?;
let algo = core.algorithm();
let key = LessSafeKey::new(UnboundKey::new(algo, &rot.key[..algo.key_len()]).unwrap());
core.rotate_key(key, rot.id, rot.use_for_sending);
}
Ok(())
}
fn encrypt_message(&mut self, buffer: &mut MsgBuffer) -> Result<(), Error> {
if self.unencrypted {
return Ok(())
}
self.get_core()?.encrypt(buffer);
Ok(())
}
fn decrypt_message(&mut self, buffer: &mut MsgBuffer) -> Result<(), Error> {
// HOT PATH
if self.unencrypted {
return Ok(())
}
self.get_core()?.decrypt(buffer)
}
pub fn handle_message(&mut self, buffer: &mut MsgBuffer) -> Result<MessageResult<P>, Error> {
// HOT PATH
if buffer.is_empty() {
return Err(Error::InvalidCryptoState("No message in buffer"))
}
if is_init_message(buffer.buffer()) {
// COLD PATH
debug!("Received init message");
buffer.take_prefix();
self.handle_init_message(buffer)
} else {
// HOT PATH
debug!("Received encrypted message");
self.decrypt_message(buffer)?;
let msg_type = buffer.take_prefix();
if msg_type == MESSAGE_TYPE_ROTATION {
// COLD PATH
debug!("Received rotation message");
self.handle_rotate_message(buffer.buffer())?;
buffer.clear();
Ok(MessageResult::None)
} else {
Ok(MessageResult::Message(msg_type))
}
}
}
pub fn send_message(&mut self, type_: u8, buffer: &mut MsgBuffer) -> Result<(), Error> {
// HOT PATH
assert_ne!(type_, MESSAGE_TYPE_ROTATION);
buffer.prepend_byte(type_);
self.encrypt_message(buffer)
}
pub fn every_second(&mut self, out: &mut MsgBuffer) -> Result<MessageResult<P>, Error> {
out.clear();
if let Some(ref mut core) = self.core {
core.every_second()
}
if let Some(ref mut init) = self.init {
init.every_second(out)?;
}
if self.init.as_ref().map(|i| i.stage()).unwrap_or(CLOSING) == CLOSING {
self.init = None
}
if !out.is_empty() {
out.prepend_byte(INIT_MESSAGE_FIRST_BYTE);
return Ok(MessageResult::Reply)
}
if let Some(ref mut rotate) = self.rotation {
self.rotate_counter += 1;
if self.rotate_counter >= ROTATE_INTERVAL {
self.rotate_counter = 0;
if let Some(rot) = rotate.cycle(out) {
let core = self.get_core()?;
let algo = core.algorithm();
let key = LessSafeKey::new(UnboundKey::new(algo, &rot.key[..algo.key_len()]).unwrap());
core.rotate_key(key, rot.id, rot.use_for_sending);
}
if !out.is_empty() {
out.prepend_byte(MESSAGE_TYPE_ROTATION);
self.encrypt_message(out)?;
return Ok(MessageResult::Reply)
}
}
}
Ok(MessageResult::None)
}
}
pub fn is_init_message(msg: &[u8]) -> bool {
// HOT PATH
!msg.is_empty() && msg[0] == INIT_MESSAGE_FIRST_BYTE
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::NODE_ID_BYTES;
fn create_node(config: &Config) -> PeerCrypto<Vec<u8>> {
let rng = SystemRandom::new();
let mut node_id = [0; NODE_ID_BYTES];
rng.fill(&mut node_id).unwrap();
let crypto = Crypto::new(node_id, config).unwrap();
crypto.peer_instance(vec![])
}
#[test]
fn normal() {
let config = Config { password: Some("test".to_string()), ..Default::default() };
let mut node1 = create_node(&config);
let mut node2 = create_node(&config);
let mut msg = MsgBuffer::new(16);
node1.initialize(&mut msg).unwrap();
assert!(!msg.is_empty());
debug!("Node1 -> Node2");
let res = node2.handle_message(&mut msg).unwrap();
assert_eq!(res, MessageResult::Reply);
assert!(!msg.is_empty());
debug!("Node1 <- Node2");
let res = node1.handle_message(&mut msg).unwrap();
assert_eq!(res, MessageResult::InitializedWithReply(vec![]));
assert!(!msg.is_empty());
debug!("Node1 -> Node2");
let res = node2.handle_message(&mut msg).unwrap();
assert_eq!(res, MessageResult::InitializedWithReply(vec![]));
assert!(!msg.is_empty());
debug!("Node1 <- Node2");
let res = node1.handle_message(&mut msg).unwrap();
assert_eq!(res, MessageResult::None);
assert!(msg.is_empty());
let mut buffer = MsgBuffer::new(16);
let rng = SystemRandom::new();
buffer.set_length(1000);
rng.fill(buffer.message_mut()).unwrap();
for _ in 0..1000 {
node1.send_message(1, &mut buffer).unwrap();
let res = node2.handle_message(&mut buffer).unwrap();
assert_eq!(res, MessageResult::Message(1));
match node1.every_second(&mut msg).unwrap() {
MessageResult::None => (),
MessageResult::Reply => {
let res = node2.handle_message(&mut msg).unwrap();
assert_eq!(res, MessageResult::None);
}
other => assert_eq!(other, MessageResult::None)
}
match node2.every_second(&mut msg).unwrap() {
MessageResult::None => (),
MessageResult::Reply => {
let res = node1.handle_message(&mut msg).unwrap();
assert_eq!(res, MessageResult::None);
}
other => assert_eq!(other, MessageResult::None)
}
}
}
}
pub use common::*;

View File

@ -1,3 +1,7 @@
// VpnCloud - Peer-to-Peer VPN
// Copyright (C) 2015-2021 Dennis Schwerdel
// This software is licensed under GPL-3 or newer (see LICENSE.md)
// This module implements a turn based key rotation.
//
// The main idea is that both peers periodically create ecdh key pairs and exchange their public keys to create
@ -25,24 +29,23 @@
//
// The whole communication is sent via the crypto stream and is therefore encrypted and protected against tampering.
use super::{Error, Key, MsgBuffer};
use super::Key;
use crate::{error::Error, util::MsgBuffer};
use byteorder::{NetworkEndian, ReadBytesExt, WriteBytesExt};
use ring::{
agreement::{agree_ephemeral, EphemeralPrivateKey, UnparsedPublicKey, X25519},
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,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::{
@ -10,7 +10,7 @@ use std::{
fs::{self, File},
io::{self, BufRead, BufReader, Cursor, Error as IoError, Read, Write},
net::{Ipv4Addr, UdpSocket},
os::unix::io::{AsRawFd, RawFd},
os::{unix::io::AsRawFd, fd::RawFd},
str,
str::FromStr
};
@ -19,18 +19,25 @@ 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 {
@ -42,7 +49,6 @@ impl IfReq {
}
}
/// The type of a tun/tap device
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
pub enum Type {
@ -51,14 +57,14 @@ pub enum Type {
Tun,
/// Tap interface: This interface transports Ethernet frames.
#[serde(rename = "tap")]
Tap
Tap,
}
impl fmt::Display for Type {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
Type::Tun => write!(formatter, "tun"),
Type::Tap => write!(formatter, "tap")
Type::Tap => write!(formatter, "tap"),
}
}
}
@ -70,7 +76,7 @@ impl FromStr for Type {
Ok(match &text.to_lowercase() as &str {
"tun" => Self::Tun,
"tap" => Self::Tap,
_ => return Err("Unknown device type")
_ => return Err("Unknown device type"),
})
}
}
@ -109,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
///
@ -142,7 +146,7 @@ impl TunTapDevice {
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::Tap => libc::IFF_TAP | libc::IFF_NO_PI,
};
let mut ifreq = IfReq::new(ifname);
ifreq.data.flags = flags as libc::c_short;
@ -155,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()),
}
}
@ -163,7 +167,7 @@ impl TunTapDevice {
#[inline]
pub fn default_path(type_: Type) -> &'static str {
match type_ {
Type::Tun | Type::Tap => "/dev/net/tun"
Type::Tun | Type::Tap => "/dev/net/tun",
}
}
@ -211,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!(),
}
}
}
@ -283,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)),
}
}
@ -299,10 +303,9 @@ impl AsRawFd for TunTapDevice {
}
}
pub struct MockDevice {
inbound: VecDeque<Vec<u8>>,
outbound: VecDeque<Vec<u8>>
outbound: VecDeque<Vec<u8>>,
}
impl MockDevice {
@ -344,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(())
}
@ -355,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) }
}
}
@ -366,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")?;
@ -375,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()),
}
}
@ -386,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()),
}
}
@ -397,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()),
}
}
@ -412,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()),
}
}
@ -428,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()),
}
}
@ -443,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()),
}
}
@ -456,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 }
@ -466,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;
@ -479,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,11 +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)
#[macro_use] extern crate log;
#[macro_use] extern crate serde;
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde;
#[cfg(test)] extern crate tempfile;
#[cfg(test)]
extern crate tempfile;
#[macro_use]
pub mod util;
@ -18,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;
@ -27,7 +32,10 @@ pub mod port_forwarding;
pub mod table;
pub mod traffic;
pub mod types;
#[cfg(feature = "websocket")] pub mod wsproxy;
#[cfg(feature = "wizard")]
pub mod wizard;
#[cfg(feature = "websocket")]
pub mod wsproxy;
use structopt::StructOpt;
@ -40,7 +48,6 @@ use std::{
process,
str::FromStr,
sync::Mutex,
thread
};
use crate::{
@ -58,7 +65,7 @@ use crate::{
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");
}
@ -106,7 +113,7 @@ impl log::Log for DualLogger {
fn run_script(script: &str, ifname: &str) {
let mut cmd = process::Command::new("sh");
cmd.arg("-c").arg(&script).env("IFNAME", ifname);
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());
@ -204,8 +211,6 @@ fn run<P: Protocol, S: Socket>(config: Config, socket: S) {
}
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() {
@ -229,7 +234,7 @@ fn main() {
let args: Args = Args::from_args();
if args.version {
println!("VpnCloud v{}", env!("CARGO_PKG_VERSION"));
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();
@ -272,14 +277,25 @@ fn main() {
}
Command::Completion { shell } => {
Args::clap().gen_completions_to(env!("CARGO_PKG_NAME"), shell, &mut io::stdout());
return
}
#[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
return;
}
let mut config = Config::default();
if let Some(ref file) = args.config {
@ -304,20 +320,20 @@ fn main() {
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
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)
Type::Tun => run::<payload::Packet, _>(config, socket),
}
return
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, socket),
Type::Tun => run::<payload::Packet, _>(config, socket)
Type::Tun => run::<payload::Packet, _>(config, socket),
}
}

View File

@ -1,35 +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)]
@ -38,7 +35,7 @@ pub struct NodeInfo {
pub peers: PeerList,
pub claims: RangeList,
pub peer_timeout: Option<u16>,
pub addrs: AddrList
pub addrs: AddrList,
}
impl NodeInfo {
@ -53,7 +50,7 @@ impl NodeInfo {
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;
@ -74,7 +71,7 @@ impl NodeInfo {
}
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 {
@ -109,7 +106,7 @@ impl NodeInfo {
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);
@ -139,7 +136,7 @@ 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, addrs })
}
@ -155,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 {
@ -190,7 +187,7 @@ impl NodeInfo {
for a in &self.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 {
@ -213,7 +210,7 @@ impl NodeInfo {
}
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)?;
@ -257,7 +254,6 @@ impl NodeInfo {
}
}
impl Payload for NodeInfo {
fn write_to(&self, buffer: &mut MsgBuffer) {
self.encode(buffer)

View File

@ -1,28 +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 std::{
collections::{HashMap, VecDeque},
io::{self, ErrorKind},
net::{IpAddr, SocketAddr, UdpSocket, Ipv6Addr},
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::port_forwarding::PortForwarding;
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").unwrap();
let s = UdpSocket::bind("0.0.0.0:0").unwrap();
s.connect("8.8.8.8:0").unwrap();
s.local_addr().unwrap().ip()
}
@ -35,21 +35,23 @@ pub trait Socket: AsRawFd + Sized {
fn create_port_forwarding(&self) -> Option<PortForwarding>;
}
pub fn parse_listen(addr: &str) -> SocketAddr {
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 {
let port = try_fail!(addr.parse::<u16>(), "Invalid port: {}");
} 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: &str) -> Result<Self, io::Error> {
let addr = parse_listen(addr);
let addr = mapped_addr(parse_listen(addr, DEFAULT_PORT));
UdpSocket::bind(addr)
}
@ -84,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 {
@ -93,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),
}
}
@ -109,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);
@ -134,7 +136,7 @@ impl AsRawFd for MockSocket {
impl Socket for MockSocket {
fn listen(addr: &str) -> Result<Self, io::Error> {
Ok(Self::new(parse_listen(addr)))
Ok(Self::new(mapped_addr(parse_listen(addr, DEFAULT_PORT))))
}
fn receive(&mut self, buffer: &mut MsgBuffer) -> Result<SocketAddr, io::Error> {
@ -149,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);
}
@ -178,4 +180,4 @@ mod bench {
b.iter(|| sock.send_to(&data, &addr).unwrap());
b.bytes = 1400;
}
}
}

View File

@ -1,3 +1,7 @@
// VpnCloud - Peer-to-Peer VPN
// Copyright (C) 2015-2021 Dennis Schwerdel
// This software is licensed under GPL-3 or newer (see LICENSE.md)
use super::{device::Type, types::Mode, util::Duration};
use crate::config::{ConfigFile, ConfigFileBeacon, ConfigFileDevice, ConfigFileStatsd, CryptoConfig};
use std::collections::HashMap;
@ -9,7 +13,7 @@ pub enum OldCryptoMethod {
#[serde(rename = "aes256")]
AES256,
#[serde(rename = "aes128")]
AES128
AES128,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Default)]
@ -53,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 {
@ -85,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 {
@ -93,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,
@ -117,7 +122,7 @@ impl OldConfigFile {
switch_timeout: self.dst_timeout,
user: self.user,
hook: None,
hooks: HashMap::new()
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};
@ -43,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 {
@ -52,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];
@ -93,13 +92,13 @@ impl Protocol for 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)?;
@ -107,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];
@ -131,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 });
@ -158,4 +156,4 @@ fn decode_invalid_packet() {
4, 3, 2
])
.is_err());
}
}

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::{io, os::unix::io::RawFd};
@ -11,7 +11,7 @@ pub struct EpollWait {
event: libc::epoll_event,
socket: RawFd,
device: RawFd,
timeout: u32
timeout: u32,
}
impl EpollWait {
@ -27,14 +27,14 @@ impl EpollWait {
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());
}
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) };
if res == -1 {
return Err(io::Error::last_os_error())
return Err(io::Error::last_os_error());
}
}
Ok(Self { poll_fd, event, socket, device, timeout })
@ -63,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> {
@ -50,6 +48,7 @@ impl<TS: TimeSource> ClaimTable<TS> {
}
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);
@ -57,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()
@ -92,7 +94,7 @@ 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;
@ -104,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
}
@ -155,4 +157,4 @@ impl<TS: TimeSource> ClaimTable<TS> {
}
}
// TODO: test
// TODO: test

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,218 +1,8 @@
// VpnCloud - Peer-to-Peer VPN
// Copyright (C) 2015-2020 Dennis Schwerdel
// Copyright (C) 2015-2021 Dennis Schwerdel
// This software is licensed under GPL-3 or newer (see LICENSE.md)
mod common;
mod nat;
mod payload;
mod peers;
use std::{
collections::{HashMap, VecDeque},
io::Write,
net::SocketAddr,
sync::{
atomic::{AtomicUsize, Ordering},
Once
}
};
pub use super::{
cloud::GenericCloud,
config::{Config, CryptoConfig},
device::{MockDevice, Type},
net::MockSocket,
payload::{Frame, Packet, Protocol},
types::Range,
util::{MockTimeSource, Time, TimeSource}
};
static INIT_LOGGER: Once = Once::new();
pub fn init_debug_logger() {
INIT_LOGGER.call_once(|| {
log::set_boxed_logger(Box::new(DebugLogger)).unwrap();
log::set_max_level(log::LevelFilter::Debug);
})
}
static CURRENT_NODE: AtomicUsize = AtomicUsize::new(0);
struct DebugLogger;
impl DebugLogger {
pub fn set_node(node: usize) {
CURRENT_NODE.store(node, Ordering::SeqCst);
}
}
impl log::Log for DebugLogger {
#[inline]
fn enabled(&self, _metadata: &log::Metadata) -> bool {
true
}
#[inline]
fn log(&self, record: &log::Record) {
if self.enabled(record.metadata()) {
eprintln!("Node {} - {} - {}", CURRENT_NODE.load(Ordering::SeqCst), record.level(), record.args());
}
}
#[inline]
fn flush(&self) {
std::io::stderr().flush().expect("Failed to flush")
}
}
type TestNode<P> = GenericCloud<MockDevice, P, MockSocket, MockTimeSource>;
pub struct Simulator<P: Protocol> {
next_port: u16,
nodes: HashMap<SocketAddr, TestNode<P>>,
messages: VecDeque<(SocketAddr, SocketAddr, Vec<u8>)>
}
pub type TapSimulator = Simulator<Frame>;
#[allow(dead_code)]
pub type TunSimulator = Simulator<Packet>;
impl<P: Protocol> Simulator<P> {
pub fn new() -> Self {
init_debug_logger();
MockTimeSource::set_time(0);
Self { next_port: 1, nodes: HashMap::default(), messages: VecDeque::default() }
}
pub fn add_node(&mut self, nat: bool, config: &Config) -> SocketAddr {
let mut config = config.clone();
MockSocket::set_nat(nat);
config.listen = format!("[::]:{}", self.next_port);
let addr = config.listen.parse::<SocketAddr>().unwrap();
if config.crypto.password.is_none() && config.crypto.private_key.is_none() {
config.crypto.password = Some("test123".to_string())
}
DebugLogger::set_node(self.next_port as usize);
self.next_port += 1;
let node = TestNode::new(&config, MockSocket::new(addr), MockDevice::new(), None, None);
DebugLogger::set_node(0);
self.nodes.insert(addr, node);
addr
}
#[allow(dead_code)]
pub fn get_node(&mut self, addr: SocketAddr) -> &mut TestNode<P> {
let node = self.nodes.get_mut(&addr).unwrap();
DebugLogger::set_node(node.get_num());
node
}
pub fn simulate_next_message(&mut self) {
if let Some((src, dst, data)) = self.messages.pop_front() {
if let Some(node) = self.nodes.get_mut(&dst) {
if node.socket().put_inbound(src, data) {
DebugLogger::set_node(node.get_num());
node.trigger_socket_event();
DebugLogger::set_node(0);
let sock = node.socket();
let src = dst;
while let Some((dst, data)) = sock.pop_outbound() {
self.messages.push_back((src, dst, data));
}
}
} else {
warn!("Message to unknown node {}", dst);
}
}
}
pub fn simulate_all_messages(&mut self) {
while !self.messages.is_empty() {
self.simulate_next_message()
}
}
pub fn trigger_node_housekeep(&mut self, addr: SocketAddr) {
let node = self.nodes.get_mut(&addr).unwrap();
DebugLogger::set_node(node.get_num());
node.trigger_housekeep();
DebugLogger::set_node(0);
let sock = node.socket();
while let Some((dst, data)) = sock.pop_outbound() {
self.messages.push_back((addr, dst, data));
}
}
pub fn trigger_housekeep(&mut self) {
for (src, node) in &mut self.nodes {
DebugLogger::set_node(node.get_num());
node.trigger_housekeep();
DebugLogger::set_node(0);
let sock = node.socket();
while let Some((dst, data)) = sock.pop_outbound() {
self.messages.push_back((*src, dst, data));
}
}
}
pub fn set_time(&mut self, time: Time) {
MockTimeSource::set_time(time);
}
pub fn simulate_time(&mut self, time: Time) {
let mut t = MockTimeSource::now();
while t < time {
t += 1;
self.set_time(t);
self.trigger_housekeep();
self.simulate_all_messages();
}
}
pub fn connect(&mut self, src: SocketAddr, dst: SocketAddr) {
let node = self.nodes.get_mut(&src).unwrap();
DebugLogger::set_node(node.get_num());
node.connect(dst).unwrap();
DebugLogger::set_node(0);
let sock = node.socket();
while let Some((dst, data)) = sock.pop_outbound() {
self.messages.push_back((src, dst, data));
}
}
pub fn is_connected(&self, src: SocketAddr, dst: SocketAddr) -> bool {
self.nodes.get(&src).unwrap().is_connected(&dst)
}
#[allow(dead_code)]
pub fn node_addresses(&self) -> Vec<SocketAddr> {
self.nodes.keys().copied().collect()
}
#[allow(dead_code)]
pub fn message_count(&self) -> usize {
self.messages.len()
}
pub fn put_payload(&mut self, addr: SocketAddr, data: Vec<u8>) {
let node = self.nodes.get_mut(&addr).unwrap();
node.device().put_inbound(data);
DebugLogger::set_node(node.get_num());
node.trigger_device_event();
DebugLogger::set_node(0);
let sock = node.socket();
while let Some((dst, data)) = sock.pop_outbound() {
self.messages.push_back((addr, dst, data));
}
}
pub fn pop_payload(&mut self, node: SocketAddr) -> Option<Vec<u8>> {
self.nodes.get_mut(&node).unwrap().device().pop_outbound()
}
pub fn drop_message(&mut self) {
self.messages.pop_front();
}
}
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,37 +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) {
// HOT PATH
self.peers.entry(peer).or_insert_with(TrafficEntry::default).count_out(bytes);
self.peers.entry(peer).or_default().count_out(bytes);
}
#[inline]
pub fn count_in_traffic(&mut self, peer: SocketAddr, bytes: usize) {
// HOT PATH
self.peers.entry(peer).or_insert_with(TrafficEntry::default).count_in(bytes);
self.peers.entry(peer).or_default().count_in(bytes);
}
#[inline]
pub fn count_out_payload(&mut self, remote: Address, local: Address, bytes: usize) {
// HOT PATH
self.payload.entry((remote, local)).or_insert_with(TrafficEntry::default).count_out(bytes);
self.payload.entry((remote, local)).or_default().count_out(bytes);
}
#[inline]
pub fn count_in_payload(&mut self, remote: Address, local: Address, bytes: usize) {
// HOT PATH
self.payload.entry((remote, local)).or_insert_with(TrafficEntry::default).count_in(bytes);
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,5 +1,5 @@
// VpnCloud - Peer-to-Peer VPN
// Copyright (C) 2015-2020 Dennis Schwerdel
// Copyright (C) 2015-2021 Dennis Schwerdel
// This software is licensed under GPL-3 or newer (see LICENSE.md)
use std::process::Command;
@ -369,7 +369,7 @@ 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),

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(())
}

View File

@ -1,20 +1,23 @@
// 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
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
thread::spawn,
};
use tungstenite::{client::AutoStream, connect, protocol::WebSocket, server::accept, Message};
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)))
@ -31,7 +34,7 @@ fn write_addr<W: Write>(addr: SocketAddr, mut out: W) -> Result<(), io::Error> {
out.write_all(&addr.ip().octets())?;
out.write_u16::<NetworkEndian>(addr.port())?;
}
_ => unreachable!()
_ => unreachable!(),
}
Ok(())
}
@ -55,14 +58,14 @@ fn serve_proxy_connection(stream: TcpStream) -> Result<(), io::Error> {
info!("Listening on {} for peer {}", addr, peer);
addr.set_ip(get_ip());
write_addr(addr, &mut msg)?;
io_error!(websocket.write_message(Message::Binary(msg)), "Failed to write to ws connection: {}")?;
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_message(), "Failed to read message on websocket {}: {}", peer)?;
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))?;
@ -77,19 +80,19 @@ fn serve_proxy_connection(stream: TcpStream) -> Result<(), io::Error> {
let mut data = Vec::with_capacity(18 + size);
write_addr(addr, &mut data)?;
data.write_all(&buffer[..size])?;
io_error!(websocket.write_message(Message::Binary(data)), "Failed to write to {}: {}", peer)?;
io_error!(websocket.send(Message::Binary(data)), "Failed to write to {}: {}", peer)?;
}
WaitResult::Timeout => {
io_error!(websocket.write_message(Message::Ping(vec![])), "Failed to send ping: {}")?;
io_error!(websocket.send(Message::Ping(vec![])), "Failed to send ping: {}")?;
}
WaitResult::Error(err) => return Err(err)
WaitResult::Error(err) => return Err(err),
}
}
Ok(())
}
pub fn run_proxy(listen: &str) -> Result<(), io::Error> {
let addr = parse_listen(listen);
let addr = parse_listen(listen, 8080);
let server = TcpListener::bind(addr)?;
info!("Listening on ws://{}", server.local_addr()?);
for stream in server.incoming() {
@ -106,14 +109,14 @@ pub fn run_proxy(listen: &str) -> Result<(), io::Error> {
pub struct ProxyConnection {
addr: SocketAddr,
socket: WebSocket<AutoStream>
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_message(), "Failed to read from ws proxy: {}")? {
return Ok(data)
if let Message::Binary(data) = io_error!(self.socket.read(), "Failed to read from ws proxy: {}")? {
return Ok(data);
}
}
}
@ -121,7 +124,10 @@ impl ProxyConnection {
impl AsRawFd for ProxyConnection {
fn as_raw_fd(&self) -> RawFd {
self.socket.get_ref().as_raw_fd()
match self.socket.get_ref() {
MaybeTlsStream::Plain(stream) => stream.as_raw_fd(),
_ => unimplemented!()
}
}
}
@ -149,7 +155,7 @@ impl Socket for ProxyConnection {
let mut msg = Vec::with_capacity(data.len() + 18);
write_addr(addr, &mut msg)?;
msg.write_all(data)?;
io_error!(self.socket.write_message(Message::Binary(msg)), "Failed to write to ws proxy: {}")?;
io_error!(self.socket.send(Message::Binary(msg)), "Failed to write to ws proxy: {}")?;
Ok(data.len())
}

View File

@ -614,5 +614,5 @@ given.
== COPYRIGHT
Copyright (C) 2015-2020 Dennis Schwerdel
Copyright (C) 2015-2021 Dennis Schwerdel
This software is licensed under GPL-3 or newer (see LICENSE.md)