mirror of
https://github.com/eycorsican/leaf.git
synced 2026-12-06 00:01:35 +00:00
Add OpenSSL and support more targets
* Added OpenSSL AEAD support * Added OpenSSL TLS support * Added mips/mipsel support OpenSSL features can be conditinally compiled, targets not supported by ring should use OpenSSL, e.g. mips/mipsel, while other targets should use ring and rustls for crypto and TLS for better performance. Crypto functions from Shadowsocks and VMess are unified in common/crypto.
This commit is contained in:
1 parent
d4567032ee
commit
ce5366ebc4
23 files changed
+986
-590
No files matched your search
+29
-30
@@ -4,22 +4,30 @@ on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
build-bin-cross:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
target:
|
||||
- aarch64-unknown-linux-gnu
|
||||
- aarch64-unknown-linux-musl
|
||||
- arm-unknown-linux-gnueabi
|
||||
- arm-unknown-linux-musleabi
|
||||
- i686-unknown-linux-gnu
|
||||
- i686-unknown-linux-musl
|
||||
# - mips-unknown-linux-gnu
|
||||
- x86_64-pc-windows-gnu
|
||||
- x86_64-unknown-linux-gnu
|
||||
- mips-unknown-linux-musl
|
||||
- mips-unknown-linux-gnu
|
||||
#- mips64-unknown-linux-gnuabi64
|
||||
- mipsel-unknown-linux-musl
|
||||
- mipsel-unknown-linux-gnu
|
||||
#- mipsel64-unknown-linux-gnuabi64
|
||||
- x86_64-unknown-linux-musl
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
- x86_64-unknown-linux-gnu
|
||||
- i686-unknown-linux-musl
|
||||
- i686-unknown-linux-gnu
|
||||
- aarch64-unknown-linux-musl
|
||||
- aarch64-unknown-linux-gnu
|
||||
- arm-unknown-linux-musleabi
|
||||
- arm-unknown-linux-gnueabi
|
||||
- armv7-unknown-linux-musleabihf
|
||||
- armv7-unknown-linux-gnueabihf
|
||||
#- i686-pc-windows-gnu
|
||||
- x86_64-pc-windows-gnu
|
||||
|
||||
steps:
|
||||
- name: checkout
|
||||
@@ -27,10 +35,6 @@ jobs:
|
||||
with:
|
||||
submodules: true
|
||||
|
||||
- name: show last commit
|
||||
run: |
|
||||
git show --summary
|
||||
|
||||
- name: install rust toolchain
|
||||
uses: hecrj/setup-rust-action@v1
|
||||
with:
|
||||
@@ -46,7 +50,7 @@ jobs:
|
||||
|
||||
- name: build
|
||||
run: |
|
||||
cross build --target ${{ matrix.target }} -p leaf-bin --release
|
||||
./misc/build_cross.sh ${{ matrix.target }}
|
||||
|
||||
- name: rename and compress artifacts
|
||||
if: ${{ matrix.target == 'x86_64-pc-windows-gnu' }}
|
||||
@@ -100,7 +104,11 @@ jobs:
|
||||
- name: install llvm
|
||||
if: ${{ matrix.os == 'macos-latest' }}
|
||||
run: |
|
||||
brew update && brew install llvm protobuf upx
|
||||
brew uninstall openssl@1.0.2t
|
||||
brew uninstall python@2.7.17
|
||||
brew untap local/openssl
|
||||
brew untap local/python2
|
||||
brew update && brew install llvm protobuf
|
||||
|
||||
- name: build
|
||||
run: |
|
||||
@@ -125,15 +133,6 @@ jobs:
|
||||
with:
|
||||
submodules: true
|
||||
|
||||
- name: show last commit
|
||||
run: |
|
||||
git show --summary
|
||||
|
||||
- name: show xcode
|
||||
run: |
|
||||
xcodebuild -version
|
||||
xcrun --sdk iphoneos --show-sdk-path
|
||||
|
||||
- name: install rust
|
||||
uses: hecrj/setup-rust-action@v1
|
||||
with:
|
||||
@@ -144,6 +143,10 @@ jobs:
|
||||
rustup target add aarch64-apple-ios
|
||||
cargo install cargo-lipo
|
||||
cargo install cbindgen
|
||||
brew uninstall openssl@1.0.2t
|
||||
brew uninstall python@2.7.17
|
||||
brew untap local/openssl
|
||||
brew untap local/python2
|
||||
brew update && brew install llvm unzip protobuf
|
||||
|
||||
- name: build
|
||||
@@ -160,10 +163,6 @@ jobs:
|
||||
mv target/universal/release/libleaf.a .
|
||||
zip libleaf-ios.zip leaf.h libleaf.a
|
||||
|
||||
- name: verify zip artifacts
|
||||
run: |
|
||||
unzip -l libleaf-ios.zip
|
||||
|
||||
- name: upload assets
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
|
||||
@@ -7,21 +7,29 @@ on:
|
||||
|
||||
jobs:
|
||||
build-bin-cross:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
target:
|
||||
- aarch64-unknown-linux-gnu
|
||||
- aarch64-unknown-linux-musl
|
||||
- arm-unknown-linux-gnueabi
|
||||
- arm-unknown-linux-musleabi
|
||||
- i686-unknown-linux-gnu
|
||||
- i686-unknown-linux-musl
|
||||
# - mips-unknown-linux-gnu
|
||||
- x86_64-pc-windows-gnu
|
||||
- x86_64-unknown-linux-gnu
|
||||
- mips-unknown-linux-musl
|
||||
- mips-unknown-linux-gnu
|
||||
#- mips64-unknown-linux-gnuabi64
|
||||
- mipsel-unknown-linux-musl
|
||||
- mipsel-unknown-linux-gnu
|
||||
#- mipsel64-unknown-linux-gnuabi64
|
||||
- x86_64-unknown-linux-musl
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
- x86_64-unknown-linux-gnu
|
||||
- i686-unknown-linux-musl
|
||||
- i686-unknown-linux-gnu
|
||||
- aarch64-unknown-linux-musl
|
||||
- aarch64-unknown-linux-gnu
|
||||
- arm-unknown-linux-musleabi
|
||||
- arm-unknown-linux-gnueabi
|
||||
- armv7-unknown-linux-musleabihf
|
||||
- armv7-unknown-linux-gnueabihf
|
||||
#- i686-pc-windows-gnu
|
||||
- x86_64-pc-windows-gnu
|
||||
|
||||
steps:
|
||||
- name: checkout
|
||||
@@ -29,10 +37,6 @@ jobs:
|
||||
with:
|
||||
submodules: true
|
||||
|
||||
- name: show last commit
|
||||
run: |
|
||||
git show --summary
|
||||
|
||||
- name: install rust toolchain
|
||||
uses: hecrj/setup-rust-action@v1
|
||||
with:
|
||||
@@ -48,7 +52,7 @@ jobs:
|
||||
|
||||
- name: build
|
||||
run: |
|
||||
cross build --target ${{ matrix.target }} -p leaf-bin --release
|
||||
./misc/build_cross.sh ${{ matrix.target }}
|
||||
|
||||
- name: rename and compress artifacts
|
||||
if: ${{ matrix.target == 'x86_64-pc-windows-gnu' }}
|
||||
@@ -90,10 +94,6 @@ jobs:
|
||||
with:
|
||||
submodules: true
|
||||
|
||||
- name: show last commit
|
||||
run: |
|
||||
git show --summary
|
||||
|
||||
- name: install rust toolchain
|
||||
uses: hecrj/setup-rust-action@v1
|
||||
with:
|
||||
@@ -102,7 +102,11 @@ jobs:
|
||||
- name: install llvm
|
||||
if: ${{ matrix.os == 'macos-latest' }}
|
||||
run: |
|
||||
brew update && brew install llvm protobuf upx
|
||||
brew uninstall openssl@1.0.2t
|
||||
brew uninstall python@2.7.17
|
||||
brew untap local/openssl
|
||||
brew untap local/python2
|
||||
brew update && brew install llvm protobuf
|
||||
|
||||
- name: build
|
||||
run: |
|
||||
@@ -127,15 +131,6 @@ jobs:
|
||||
with:
|
||||
submodules: true
|
||||
|
||||
- name: show last commit
|
||||
run: |
|
||||
git show --summary
|
||||
|
||||
- name: show xcode
|
||||
run: |
|
||||
xcodebuild -version
|
||||
xcrun --sdk iphoneos --show-sdk-path
|
||||
|
||||
- name: install rust
|
||||
uses: hecrj/setup-rust-action@v1
|
||||
with:
|
||||
@@ -146,6 +141,10 @@ jobs:
|
||||
rustup target add aarch64-apple-ios
|
||||
cargo install cargo-lipo
|
||||
cargo install cbindgen
|
||||
brew uninstall openssl@1.0.2t
|
||||
brew uninstall python@2.7.17
|
||||
brew untap local/openssl
|
||||
brew untap local/python2
|
||||
brew update && brew install llvm unzip protobuf
|
||||
|
||||
- name: build
|
||||
@@ -210,16 +209,24 @@ jobs:
|
||||
matrix:
|
||||
target:
|
||||
- x86_64-apple-darwin
|
||||
- aarch64-unknown-linux-gnu
|
||||
- aarch64-unknown-linux-musl
|
||||
- arm-unknown-linux-gnueabi
|
||||
- arm-unknown-linux-musleabi
|
||||
- i686-unknown-linux-gnu
|
||||
- i686-unknown-linux-musl
|
||||
# - mips-unknown-linux-gnu
|
||||
- x86_64-pc-windows-gnu
|
||||
- x86_64-unknown-linux-gnu
|
||||
- mips-unknown-linux-musl
|
||||
- mips-unknown-linux-gnu
|
||||
#- mips64-unknown-linux-gnuabi64
|
||||
- mipsel-unknown-linux-musl
|
||||
- mipsel-unknown-linux-gnu
|
||||
#- mipsel64-unknown-linux-gnuabi64
|
||||
- x86_64-unknown-linux-musl
|
||||
- x86_64-unknown-linux-gnu
|
||||
- i686-unknown-linux-musl
|
||||
- i686-unknown-linux-gnu
|
||||
- aarch64-unknown-linux-musl
|
||||
- aarch64-unknown-linux-gnu
|
||||
- arm-unknown-linux-musleabi
|
||||
- arm-unknown-linux-gnueabi
|
||||
- armv7-unknown-linux-musleabihf
|
||||
- armv7-unknown-linux-gnueabihf
|
||||
#- i686-pc-windows-gnu
|
||||
- x86_64-pc-windows-gnu
|
||||
|
||||
steps:
|
||||
- name: download upload url
|
||||
@@ -254,10 +261,6 @@ jobs:
|
||||
run: |
|
||||
zip -9 leaf-${{ matrix.target }}.zip leaf-${{ matrix.target }}.exe
|
||||
|
||||
- name: show files
|
||||
run: |
|
||||
ls -R
|
||||
|
||||
- name: upload asset
|
||||
id: upload-release-asset
|
||||
uses: actions/upload-release-asset@v1
|
||||
@@ -286,6 +289,10 @@ jobs:
|
||||
|
||||
- name: install deps
|
||||
run: |
|
||||
brew uninstall openssl@1.0.2t
|
||||
brew uninstall python@2.7.17
|
||||
brew untap local/openssl
|
||||
brew untap local/python2
|
||||
brew update && brew install unzip
|
||||
|
||||
- name: download asset
|
||||
@@ -293,10 +300,6 @@ jobs:
|
||||
with:
|
||||
name: libleaf-ios.zip
|
||||
|
||||
- name: verify zip artifacts
|
||||
run: |
|
||||
unzip -l libleaf-ios.zip
|
||||
|
||||
- name: upload asset
|
||||
id: upload-release-asset
|
||||
uses: actions/upload-release-asset@v1
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
ios:
|
||||
cargo lipo -p leaf-mobile --release --targets aarch64-apple-ios && cp target/universal/release/libleaf.a /tmp/ && cbindgen leaf-mobile/src/lib.rs -l c > /tmp/leaf.h
|
||||
cargo lipo -p leaf-mobile --release --targets aarch64-apple-ios && cbindgen leaf-mobile/src/lib.rs -l c > target/universal/release/leaf.h
|
||||
|
||||
ios-dev:
|
||||
cargo lipo -p leaf-mobile --targets aarch64-apple-ios && cp target/universal/debug/libleaf.a /tmp/ && cbindgen leaf-mobile/src/lib.rs -l c > /tmp/leaf.h
|
||||
cargo lipo -p leaf-mobile --targets aarch64-apple-ios && cbindgen leaf-mobile/src/lib.rs -l c > target/universal/debug/leaf.h
|
||||
|
||||
local:
|
||||
cargo build -p leaf-bin --release
|
||||
|
||||
+17
-4
@@ -8,13 +8,26 @@ edition = "2018"
|
||||
name = "leaf"
|
||||
path = "src/main.rs"
|
||||
|
||||
[features]
|
||||
default = ["common", "config", "ring-aead", "rustls-tls"]
|
||||
|
||||
config = ["json-config", "conf-config"]
|
||||
|
||||
json-config = ["leaf/json"]
|
||||
conf-config = ["leaf/conf"]
|
||||
|
||||
ring-aead = ["leaf/ring-aead"]
|
||||
openssl-aead = ["leaf/openssl-aead"]
|
||||
|
||||
rustls-tls = ["leaf/rustls-tls"]
|
||||
openssl-tls = ["leaf/openssl-tls"]
|
||||
|
||||
common = ["leaf/endpoint", "leaf/ensemble"]
|
||||
|
||||
[dependencies]
|
||||
leaf = { path = "../leaf" }
|
||||
leaf = { path = "../leaf", default-features = false, optional = true }
|
||||
clap = { version = "3.0.0-beta.1", default-features = false, features =["std"] }
|
||||
log = { version = "0.4", features = ["std"] }
|
||||
fern = { version = "0.5", features = ["colored"] }
|
||||
tokio = { version = "0.2", features = ["signal"] }
|
||||
futures = "0.3"
|
||||
|
||||
# [target.'cfg(not(target_env = "msvc"))'.dependencies]
|
||||
# jemallocator = "0.3.2"
|
||||
@@ -1,12 +1,5 @@
|
||||
use std::process::exit;
|
||||
|
||||
// #[cfg(not(target_env = "msvc"))]
|
||||
// use jemallocator::Jemalloc;
|
||||
//
|
||||
// #[cfg(not(target_env = "msvc"))]
|
||||
// #[global_allocator]
|
||||
// static GLOBAL: Jemalloc = Jemalloc;
|
||||
|
||||
use clap::{App, Arg};
|
||||
use log::*;
|
||||
|
||||
|
||||
+16
-5
@@ -10,7 +10,13 @@ name = "leaf"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[features]
|
||||
default = ["config", "endpoint", "ensemble"]
|
||||
default = ["config", "endpoint", "ensemble", "openssl-aead", "openssl-tls"]
|
||||
|
||||
ring-aead = ["ring"]
|
||||
openssl-aead = ["openssl"]
|
||||
|
||||
rustls-tls = ["tokio-rustls", "webpki-roots"]
|
||||
openssl-tls = ["openssl", "tokio-openssl", "openssl-probe"]
|
||||
|
||||
config = ["conf", "json"]
|
||||
|
||||
@@ -52,7 +58,6 @@ protobuf = "2.17"
|
||||
fern = { version = "0.5", features = ["colored"] }
|
||||
socket2 = "0.3"
|
||||
memmap = "0.7.0"
|
||||
ring = "0.16"
|
||||
log = { version = "0.4", features = ["std"] }
|
||||
thiserror = "1.0"
|
||||
futures = "0.3"
|
||||
@@ -82,17 +87,23 @@ chrono = "0.4"
|
||||
httparse = "1.3"
|
||||
http = "0.2"
|
||||
|
||||
openssl = { version = "0.10", features = ["vendored"], optional = true }
|
||||
ring = { version = "0.16", optional = true }
|
||||
|
||||
serde_json = { version = "1.0", features = ["raw_value"], optional = true }
|
||||
serde_derive = { version = "1.0", optional = true }
|
||||
serde = { version = "1.0", optional = true }
|
||||
|
||||
regex = { version = "1.3", default-features=false, features=["std", "perf"], optional = true }
|
||||
|
||||
tokio-rustls = { version = "0.14", features = ["dangerous_configuration"] }
|
||||
webpki-roots = "0.20"
|
||||
tokio-rustls = { version = "0.14", optional = true }
|
||||
webpki-roots = { version = "0.20", optional = true }
|
||||
|
||||
openssl-probe = { version = "0.1.2", optional = true }
|
||||
tokio-openssl = { version = "0.4", optional = true }
|
||||
|
||||
[target.'cfg(any(target_os = "ios", target_os = "macos", target_os = "linux"))'.dependencies]
|
||||
tun = { git = "https://github.com/eycorsican/rust-tun.git", branch = "trim", features = ["async"] }
|
||||
tun = { git = "https://github.com/eycorsican/rust-tun.git", branch = "fix", features = ["async"] }
|
||||
|
||||
[build-dependencies]
|
||||
cc = "1.0"
|
||||
|
||||
@@ -287,11 +287,7 @@ fn log_tcp(tag: &String, tag_color: colored::Color, handshake_time: u128, addr:
|
||||
{
|
||||
info!(
|
||||
"[{}] [{}] [{}ms] {}",
|
||||
"tcp".color(colored::Color::TrueColor {
|
||||
r: 107,
|
||||
g: 208,
|
||||
b: 255,
|
||||
}),
|
||||
"tcp".color(colored::Color::Blue),
|
||||
tag.color(tag_color),
|
||||
handshake_time,
|
||||
addr,
|
||||
@@ -308,11 +304,7 @@ fn log_udp(tag: &String, tag_color: colored::Color, handshake_time: u128, addr:
|
||||
{
|
||||
info!(
|
||||
"[{}] [{}] [{}ms] {}",
|
||||
"udp".color(colored::Color::TrueColor {
|
||||
r: 255,
|
||||
g: 193,
|
||||
b: 107,
|
||||
}),
|
||||
"udp".color(colored::Color::Yellow),
|
||||
tag.color(tag_color),
|
||||
handshake_time,
|
||||
addr,
|
||||
|
||||
+392
-10
@@ -1,15 +1,397 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
use lazy_static::lazy_static;
|
||||
use ring::aead::{self, Algorithm};
|
||||
|
||||
lazy_static! {
|
||||
pub static ref AEAD_LIST: HashMap<&'static str, &'static Algorithm> = {
|
||||
let mut m = HashMap::new();
|
||||
m.insert("chacha20-poly1305", &aead::CHACHA20_POLY1305);
|
||||
m.insert("chacha20-ietf-poly1305", &aead::CHACHA20_POLY1305);
|
||||
m.insert("aes-128-gcm", &aead::AES_128_GCM);
|
||||
m.insert("aes-256-gcm", &aead::AES_256_GCM);
|
||||
m
|
||||
};
|
||||
pub trait Cipher<N>: Sync + Send + Unpin
|
||||
where
|
||||
N: NonceSequence,
|
||||
{
|
||||
type Enc;
|
||||
type Dec;
|
||||
|
||||
fn encryptor(&self, key: &[u8], nonce: N) -> Result<Self::Enc>;
|
||||
fn decryptor(&self, key: &[u8], nonce: N) -> Result<Self::Dec>;
|
||||
}
|
||||
|
||||
pub trait SizedCipher {
|
||||
fn key_len(&self) -> usize;
|
||||
fn nonce_len(&self) -> usize;
|
||||
|
||||
fn tag_len(&self) -> usize {
|
||||
// All AEAD ciphers we support use 128-bit tags.
|
||||
16
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Encryptor: Sync + Send + Unpin {
|
||||
fn encrypt<InOut>(&mut self, in_out: &mut InOut) -> Result<()>
|
||||
where
|
||||
InOut: AsRef<[u8]> + AsMut<[u8]> + for<'in_out> Extend<&'in_out u8>;
|
||||
}
|
||||
|
||||
pub trait Decryptor: Sync + Send + Unpin {
|
||||
fn decrypt<InOut>(&mut self, in_out: &mut InOut) -> Result<()>
|
||||
where
|
||||
InOut: AsRef<[u8]> + AsMut<[u8]> + for<'in_out> Extend<&'in_out u8>;
|
||||
}
|
||||
|
||||
pub trait NonceSequence: Sync + Send + Unpin {
|
||||
fn advance(&mut self) -> Result<Vec<u8>>;
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-aead")]
|
||||
pub mod aead {
|
||||
use openssl::symm;
|
||||
|
||||
use super::*;
|
||||
|
||||
lazy_static! {
|
||||
static ref AEAD_LIST: HashMap<&'static str, symm::Cipher> = {
|
||||
let mut m = HashMap::new();
|
||||
m.insert("chacha20-poly1305", symm::Cipher::chacha20_poly1305());
|
||||
m.insert("chacha20-ietf-poly1305", symm::Cipher::chacha20_poly1305());
|
||||
m.insert("aes-256-gcm", symm::Cipher::aes_256_gcm());
|
||||
m.insert("aes-128-gcm", symm::Cipher::aes_128_gcm());
|
||||
m
|
||||
};
|
||||
}
|
||||
|
||||
pub struct AeadCipher {
|
||||
cipher: symm::Cipher,
|
||||
}
|
||||
|
||||
impl AeadCipher {
|
||||
pub fn new(cipher: &str) -> Result<Self> {
|
||||
let alg = match AEAD_LIST.get(cipher) {
|
||||
Some(v) => v,
|
||||
None => return Err(anyhow!("unsupported cipher: {}", cipher)),
|
||||
};
|
||||
Ok(AeadCipher { cipher: *alg })
|
||||
}
|
||||
}
|
||||
|
||||
impl<N> Cipher<N> for AeadCipher
|
||||
where
|
||||
N: 'static + NonceSequence,
|
||||
{
|
||||
type Enc = AeadEncryptor<N>;
|
||||
type Dec = AeadDecryptor<N>;
|
||||
|
||||
fn encryptor(&self, key: &[u8], nonce: N) -> Result<Self::Enc> {
|
||||
Ok(AeadEncryptor::new(
|
||||
self.cipher,
|
||||
key.to_vec(),
|
||||
nonce,
|
||||
self.tag_len(),
|
||||
))
|
||||
}
|
||||
|
||||
fn decryptor(&self, key: &[u8], nonce: N) -> Result<Self::Dec> {
|
||||
Ok(AeadDecryptor::new(
|
||||
self.cipher,
|
||||
key.to_vec(),
|
||||
nonce,
|
||||
self.tag_len(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl SizedCipher for AeadCipher {
|
||||
fn key_len(&self) -> usize {
|
||||
self.cipher.key_len()
|
||||
}
|
||||
|
||||
fn nonce_len(&self) -> usize {
|
||||
// All AEAD ciphers use IV.
|
||||
self.cipher.iv_len().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AeadEncryptor<N> {
|
||||
cipher: symm::Cipher,
|
||||
key: Vec<u8>,
|
||||
nonce: N,
|
||||
tag_len: usize,
|
||||
}
|
||||
|
||||
impl<N> AeadEncryptor<N>
|
||||
where
|
||||
N: NonceSequence,
|
||||
{
|
||||
pub fn new(cipher: symm::Cipher, key: Vec<u8>, nonce: N, tag_len: usize) -> Self {
|
||||
AeadEncryptor {
|
||||
cipher,
|
||||
key,
|
||||
nonce,
|
||||
tag_len,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<N> Encryptor for AeadEncryptor<N>
|
||||
where
|
||||
N: NonceSequence,
|
||||
{
|
||||
fn encrypt<InOut>(&mut self, in_out: &mut InOut) -> Result<()>
|
||||
where
|
||||
InOut: AsRef<[u8]> + AsMut<[u8]> + for<'in_out> Extend<&'in_out u8>,
|
||||
{
|
||||
let nonce = self
|
||||
.nonce
|
||||
.advance()
|
||||
.map_err(|e| anyhow!("encrypt failed: {}", e))?;
|
||||
let mut tag = vec![0u8; self.tag_len];
|
||||
// TODO in-place?
|
||||
let ciphertext = symm::encrypt_aead(
|
||||
self.cipher,
|
||||
&self.key,
|
||||
Some(&nonce),
|
||||
&[],
|
||||
in_out.as_ref(),
|
||||
&mut tag,
|
||||
)
|
||||
.map_err(|e| anyhow!("encrypt failed: {}", e))?;
|
||||
(&mut in_out.as_mut()[..ciphertext.len()]).copy_from_slice(&ciphertext);
|
||||
in_out.extend(&tag);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AeadDecryptor<N> {
|
||||
cipher: symm::Cipher,
|
||||
key: Vec<u8>,
|
||||
nonce: N,
|
||||
tag_len: usize,
|
||||
}
|
||||
|
||||
impl<N> AeadDecryptor<N>
|
||||
where
|
||||
N: NonceSequence,
|
||||
{
|
||||
pub fn new(cipher: symm::Cipher, key: Vec<u8>, nonce: N, tag_len: usize) -> Self {
|
||||
AeadDecryptor {
|
||||
cipher,
|
||||
key,
|
||||
nonce,
|
||||
tag_len,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<N> Decryptor for AeadDecryptor<N>
|
||||
where
|
||||
N: NonceSequence,
|
||||
{
|
||||
fn decrypt<InOut>(&mut self, in_out: &mut InOut) -> Result<()>
|
||||
where
|
||||
InOut: AsRef<[u8]> + AsMut<[u8]> + for<'in_out> Extend<&'in_out u8>,
|
||||
{
|
||||
let nonce = self
|
||||
.nonce
|
||||
.advance()
|
||||
.map_err(|e| anyhow!("decrypt failed: {}", e))?;
|
||||
let in_out_ref = in_out.as_ref();
|
||||
let data = &in_out_ref[..in_out_ref.len() - self.tag_len];
|
||||
let tag = &in_out_ref[in_out_ref.len() - self.tag_len..];
|
||||
// TODO in-place?
|
||||
let plaintext =
|
||||
symm::decrypt_aead(self.cipher, &self.key, Some(&nonce), &[], data, tag)
|
||||
.map_err(|e| anyhow!("decrypt failed: {}", e))?;
|
||||
(&mut in_out.as_mut()[..plaintext.len()]).copy_from_slice(&plaintext);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "ring-aead")]
|
||||
pub mod aead {
|
||||
use ring::aead::{self, Aad, Algorithm, LessSafeKey, Nonce, UnboundKey};
|
||||
|
||||
use super::*;
|
||||
|
||||
lazy_static! {
|
||||
static ref AEAD_LIST: HashMap<&'static str, &'static Algorithm> = {
|
||||
let mut m = HashMap::new();
|
||||
m.insert("chacha20-poly1305", &aead::CHACHA20_POLY1305);
|
||||
m.insert("chacha20-ietf-poly1305", &aead::CHACHA20_POLY1305);
|
||||
m.insert("aes-256-gcm", &aead::AES_256_GCM);
|
||||
m.insert("aes-128-gcm", &aead::AES_128_GCM);
|
||||
m
|
||||
};
|
||||
}
|
||||
|
||||
pub struct AeadCipher {
|
||||
algorithm: &'static Algorithm,
|
||||
}
|
||||
|
||||
impl AeadCipher {
|
||||
pub fn new(cipher: &str) -> Result<Self> {
|
||||
let alg = match AEAD_LIST.get(cipher) {
|
||||
Some(v) => v,
|
||||
None => return Err(anyhow!("unsupported cipher: {}", cipher)),
|
||||
};
|
||||
Ok(AeadCipher { algorithm: alg })
|
||||
}
|
||||
}
|
||||
|
||||
impl<N> Cipher<N> for AeadCipher
|
||||
where
|
||||
N: 'static + NonceSequence,
|
||||
{
|
||||
type Enc = AeadEncryptor<N>;
|
||||
type Dec = AeadDecryptor<N>;
|
||||
|
||||
fn encryptor(&self, key: &[u8], nonce: N) -> Result<Self::Enc> {
|
||||
let unbound_key = UnboundKey::new(self.algorithm, key)
|
||||
.map_err(|e| anyhow!("new unbound key failed: {}", e))?;
|
||||
let enc = AeadEncryptor {
|
||||
enc: LessSafeKey::new(unbound_key),
|
||||
nonce,
|
||||
};
|
||||
Ok(enc)
|
||||
}
|
||||
|
||||
fn decryptor(&self, key: &[u8], nonce: N) -> Result<Self::Dec> {
|
||||
let unbound_key = UnboundKey::new(self.algorithm, key)
|
||||
.map_err(|e| anyhow!("new unbound key failed: {}", e))?;
|
||||
let enc = AeadDecryptor {
|
||||
enc: LessSafeKey::new(unbound_key),
|
||||
nonce,
|
||||
};
|
||||
Ok(enc)
|
||||
}
|
||||
}
|
||||
|
||||
impl SizedCipher for AeadCipher {
|
||||
fn key_len(&self) -> usize {
|
||||
self.algorithm.key_len()
|
||||
}
|
||||
|
||||
fn nonce_len(&self) -> usize {
|
||||
self.algorithm.nonce_len()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AeadEncryptor<N> {
|
||||
enc: LessSafeKey,
|
||||
nonce: N,
|
||||
}
|
||||
|
||||
impl<N> AeadEncryptor<N>
|
||||
where
|
||||
N: NonceSequence,
|
||||
{
|
||||
pub fn new(enc: LessSafeKey, nonce: N) -> Self {
|
||||
AeadEncryptor { enc, nonce }
|
||||
}
|
||||
}
|
||||
|
||||
impl<N> Encryptor for AeadEncryptor<N>
|
||||
where
|
||||
N: NonceSequence,
|
||||
{
|
||||
fn encrypt<InOut>(&mut self, in_out: &mut InOut) -> Result<()>
|
||||
where
|
||||
InOut: AsRef<[u8]> + AsMut<[u8]> + for<'in_out> Extend<&'in_out u8>,
|
||||
{
|
||||
let nonce = self
|
||||
.nonce
|
||||
.advance()
|
||||
.map_err(|e| anyhow!("encrypt failed: {}", e))?;
|
||||
let nonce = Nonce::try_assume_unique_for_key(&nonce)
|
||||
.map_err(|e| anyhow!("encrypt failed: {}", e))?;
|
||||
self.enc
|
||||
.seal_in_place_append_tag(nonce, Aad::empty(), in_out)
|
||||
.map_err(|e| anyhow!("encrypt failed: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AeadDecryptor<N> {
|
||||
enc: LessSafeKey,
|
||||
nonce: N,
|
||||
}
|
||||
|
||||
impl<N> AeadDecryptor<N>
|
||||
where
|
||||
N: NonceSequence,
|
||||
{
|
||||
pub fn new(enc: LessSafeKey, nonce: N) -> Self {
|
||||
AeadDecryptor { enc, nonce }
|
||||
}
|
||||
}
|
||||
|
||||
impl<N> Decryptor for AeadDecryptor<N>
|
||||
where
|
||||
N: NonceSequence,
|
||||
{
|
||||
fn decrypt<InOut>(&mut self, in_out: &mut InOut) -> Result<()>
|
||||
where
|
||||
InOut: AsRef<[u8]> + AsMut<[u8]> + for<'in_out> Extend<&'in_out u8>,
|
||||
{
|
||||
let nonce = self
|
||||
.nonce
|
||||
.advance()
|
||||
.map_err(|e| anyhow!("encrypt failed: {}", e))?;
|
||||
let nonce = Nonce::try_assume_unique_for_key(&nonce)
|
||||
.map_err(|e| anyhow!("encrypt failed: {}", e))?;
|
||||
self.enc
|
||||
.open_within(nonce, Aad::empty(), in_out.as_mut(), 0..)
|
||||
.map_err(|e| anyhow!("encrypt failed: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_aead_enc_dec() {
|
||||
struct ShadowsocksNonceSequence(Vec<u8>);
|
||||
|
||||
impl ShadowsocksNonceSequence {
|
||||
fn new(size: usize) -> Self {
|
||||
let mut c = Vec::new();
|
||||
for _ in 0..size {
|
||||
c.push(0xff);
|
||||
}
|
||||
ShadowsocksNonceSequence(c)
|
||||
}
|
||||
|
||||
fn inc(&mut self) {
|
||||
for x in &mut self.0 {
|
||||
*x = (*x).wrapping_add(1);
|
||||
if *x != 0 {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NonceSequence for ShadowsocksNonceSequence {
|
||||
fn advance(&mut self) -> Result<Vec<u8>> {
|
||||
self.inc();
|
||||
Ok(self.0.clone())
|
||||
}
|
||||
}
|
||||
let plaintext = b"Hello, world!";
|
||||
let cipher = aead::AeadCipher::new("chacha20-poly1305").unwrap();
|
||||
let key = vec![0u8; cipher.key_len()];
|
||||
|
||||
let mut buf = Vec::new();
|
||||
buf.extend_from_slice(plaintext);
|
||||
|
||||
let nonce = ShadowsocksNonceSequence::new(cipher.nonce_len());
|
||||
let mut enc = cipher.encryptor(&key, nonce).unwrap();
|
||||
enc.encrypt(&mut buf).unwrap();
|
||||
|
||||
let dec_nonce = ShadowsocksNonceSequence::new(cipher.nonce_len());
|
||||
let mut dec = cipher.decryptor(&key, dec_nonce).unwrap();
|
||||
dec.decrypt(&mut buf).unwrap();
|
||||
|
||||
assert_eq!(&buf[..plaintext.len()], plaintext);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ pub mod dns_client;
|
||||
pub mod log;
|
||||
pub mod mutex;
|
||||
pub mod resolver;
|
||||
pub mod tls;
|
||||
|
||||
#[cfg(any(target_os = "ios", target_os = "macos", target_os = "linux"))]
|
||||
pub mod fake_dns;
|
||||
@@ -0,0 +1,126 @@
|
||||
use anyhow::{anyhow, Result};
|
||||
use futures::TryFutureExt;
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
|
||||
use crate::proxy::{ProxyStream, SimpleStream};
|
||||
|
||||
#[cfg(feature = "rustls-tls")]
|
||||
pub mod wrapper {
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio_rustls::{rustls::ClientConfig, webpki::DNSNameRef, TlsConnector};
|
||||
|
||||
use super::*;
|
||||
|
||||
// struct InsecureVerifier;
|
||||
|
||||
// impl rustls::ServerCertVerifier for InsecureVerifier {
|
||||
// fn verify_server_cert(
|
||||
// &self,
|
||||
// _roots: &rustls::RootCertStore,
|
||||
// _presented_certs: &[rustls::Certificate],
|
||||
// _dns_name: DNSNameRef<'_>,
|
||||
// _ocsp_response: &[u8],
|
||||
// ) -> Result<rustls::ServerCertVerified, rustls::TLSError> {
|
||||
// Ok(rustls::ServerCertVerified::assertion())
|
||||
// }
|
||||
// }
|
||||
|
||||
pub async fn wrap_tls<S>(
|
||||
stream: S,
|
||||
domain: &str,
|
||||
alpns: Vec<String>,
|
||||
// insecure: bool,
|
||||
) -> Result<Box<dyn ProxyStream>>
|
||||
where
|
||||
S: 'static + AsyncRead + AsyncWrite + Unpin + Sync + Send,
|
||||
{
|
||||
let mut config = ClientConfig::new();
|
||||
config
|
||||
.root_store
|
||||
.add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);
|
||||
|
||||
for alpn in alpns {
|
||||
config.alpn_protocols.push(alpn.as_bytes().to_vec());
|
||||
}
|
||||
|
||||
// if insecure {
|
||||
// let mut dangerous_config = config.dangerous();
|
||||
// dangerous_config.set_certificate_verifier(Arc::new(InsecureVerifier));
|
||||
// }
|
||||
|
||||
let config = TlsConnector::from(Arc::new(config));
|
||||
let dnsname = DNSNameRef::try_from_ascii_str(domain)
|
||||
.map_err(|e| anyhow!(format!("invalid domain: {}", e)))?;
|
||||
let tls_stream = config
|
||||
.connect(dnsname, stream)
|
||||
.map_err(|e| anyhow!(format!("tls connect failed: {}", e)))
|
||||
.await?;
|
||||
// FIXME check negotiated alpn
|
||||
Ok(Box::new(SimpleStream(tls_stream)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-tls")]
|
||||
pub mod wrapper {
|
||||
use std::sync::Once;
|
||||
|
||||
use openssl::ssl::{SslConnector, SslMethod};
|
||||
|
||||
use super::*;
|
||||
|
||||
pub async fn wrap_tls<S>(
|
||||
stream: S,
|
||||
domain: &str,
|
||||
alpns: Vec<String>,
|
||||
// insecure: bool,
|
||||
) -> Result<Box<dyn ProxyStream>>
|
||||
where
|
||||
S: 'static + AsyncRead + AsyncWrite + Unpin + Sync + Send,
|
||||
{
|
||||
{
|
||||
static ONCE: Once = Once::new();
|
||||
ONCE.call_once(openssl_probe::init_ssl_cert_env_vars);
|
||||
}
|
||||
|
||||
let mut builder = SslConnector::builder(SslMethod::tls())
|
||||
.map_err(|e| anyhow!(format!("create tls builder failed: {}", e)))?;
|
||||
|
||||
if alpns.len() > 0 {
|
||||
let wire = alpns
|
||||
.into_iter()
|
||||
.map(|a| [&[a.len() as u8], a.as_bytes()].concat())
|
||||
.collect::<Vec<Vec<u8>>>()
|
||||
.concat();
|
||||
builder
|
||||
.set_alpn_protos(&wire)
|
||||
.map_err(|e| anyhow!(format!("set alpn failed: {}", e)))?;
|
||||
}
|
||||
|
||||
let config = builder
|
||||
.build()
|
||||
.configure()
|
||||
.map_err(|e| anyhow!(format!("configure tls failed: {}", e)))?;
|
||||
let stream = tokio_openssl::connect(config, domain, stream)
|
||||
.map_err(|_| anyhow!(format!("connect tls failed")))
|
||||
.await?;
|
||||
Ok(Box::new(SimpleStream(stream)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn test_alpns_list_to_wire() {
|
||||
let mut alpns = Vec::new();
|
||||
alpns.push("h2".to_string());
|
||||
alpns.push("http/1.1".to_string());
|
||||
let expected = b"\x02h2\x08http/1.1";
|
||||
let wire = alpns
|
||||
.into_iter()
|
||||
.map(|a| [&[a.len() as u8], a.as_bytes()].concat())
|
||||
.collect::<Vec<Vec<u8>>>()
|
||||
.concat();
|
||||
assert_eq!(wire, expected);
|
||||
}
|
||||
}
|
||||
@@ -1,200 +1,24 @@
|
||||
use std::{collections::HashMap, convert::From};
|
||||
|
||||
use anyhow::anyhow;
|
||||
use anyhow::Result;
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use hkdf::Hkdf;
|
||||
use lazy_static::lazy_static;
|
||||
use md5::{Digest, Md5};
|
||||
use ring::{
|
||||
aead::{
|
||||
self, Aad, Algorithm, BoundKey, Nonce, NonceSequence, OpeningKey, SealingKey, UnboundKey,
|
||||
NONCE_LEN,
|
||||
},
|
||||
error::Unspecified,
|
||||
};
|
||||
use sha1::Sha1;
|
||||
|
||||
struct AeadAlgorithm {
|
||||
key_size: usize,
|
||||
salt_size: usize,
|
||||
algorithm: &'static Algorithm,
|
||||
}
|
||||
use crate::common::crypto::NonceSequence;
|
||||
|
||||
lazy_static! {
|
||||
static ref AEAD_LIST: HashMap<&'static str, AeadAlgorithm> = {
|
||||
let mut m = HashMap::new();
|
||||
m.insert(
|
||||
"chacha20-poly1305",
|
||||
AeadAlgorithm {
|
||||
key_size: 32,
|
||||
salt_size: 32,
|
||||
algorithm: &aead::CHACHA20_POLY1305,
|
||||
},
|
||||
);
|
||||
m.insert(
|
||||
"chacha20-ietf-poly1305",
|
||||
AeadAlgorithm {
|
||||
key_size: 32,
|
||||
salt_size: 32,
|
||||
algorithm: &aead::CHACHA20_POLY1305,
|
||||
},
|
||||
);
|
||||
m.insert(
|
||||
"aes-256-gcm",
|
||||
AeadAlgorithm {
|
||||
key_size: 32,
|
||||
salt_size: 32,
|
||||
algorithm: &aead::AES_256_GCM,
|
||||
},
|
||||
);
|
||||
m.insert(
|
||||
"aes-128-gcm",
|
||||
AeadAlgorithm {
|
||||
key_size: 16,
|
||||
salt_size: 16,
|
||||
algorithm: &aead::AES_128_GCM,
|
||||
},
|
||||
);
|
||||
m
|
||||
};
|
||||
}
|
||||
pub struct ShadowsocksNonceSequence(Vec<u8>);
|
||||
|
||||
pub fn list_ciphers() {
|
||||
for key in AEAD_LIST.keys() {
|
||||
println!("{}", key);
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Cipher: Sync + Send + Unpin {
|
||||
fn key_size(&self) -> usize;
|
||||
fn salt_size(&self) -> usize;
|
||||
fn tag_len(&self) -> usize;
|
||||
fn encryptor(&self, salt: &[u8]) -> Result<Box<dyn Encryptor>>;
|
||||
fn decryptor(&self, salt: &[u8]) -> Result<Box<dyn Decryptor>>;
|
||||
}
|
||||
|
||||
pub struct AeadCipher {
|
||||
psk: Bytes,
|
||||
key_size: usize,
|
||||
salt_size: usize,
|
||||
algorithm: &'static Algorithm,
|
||||
}
|
||||
|
||||
impl AeadCipher {
|
||||
pub fn new(cipher: &str, password: &str) -> Result<Self> {
|
||||
let (ks, ss, alg) = if let Some(v) = AEAD_LIST.get(cipher) {
|
||||
(v.key_size, v.salt_size, v.algorithm)
|
||||
} else {
|
||||
return Err(anyhow!("unsupported cipher: {}", cipher));
|
||||
};
|
||||
let psk = kdf(password, ks)?;
|
||||
Ok(AeadCipher {
|
||||
psk: Bytes::from(psk),
|
||||
key_size: ks,
|
||||
salt_size: ss,
|
||||
algorithm: alg,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Cipher for AeadCipher {
|
||||
fn key_size(&self) -> usize {
|
||||
self.key_size
|
||||
}
|
||||
|
||||
fn salt_size(&self) -> usize {
|
||||
self.salt_size
|
||||
}
|
||||
|
||||
fn tag_len(&self) -> usize {
|
||||
self.algorithm.tag_len()
|
||||
}
|
||||
|
||||
fn encryptor(&self, salt: &[u8]) -> Result<Box<dyn Encryptor>> {
|
||||
let subkey = hkdf_sha1(
|
||||
self.psk.as_ref(),
|
||||
salt,
|
||||
String::from("ss-subkey").as_bytes().to_vec(),
|
||||
self.key_size,
|
||||
)?;
|
||||
let unbound_key = UnboundKey::new(self.algorithm, &subkey)
|
||||
.map_err(|_| anyhow!("new unbound key failed"))?;
|
||||
let nonce = IncSequence::new(NONCE_LEN);
|
||||
Ok(Box::new(AeadEncryptor(SealingKey::new(unbound_key, nonce))))
|
||||
}
|
||||
|
||||
fn decryptor(&self, salt: &[u8]) -> Result<Box<dyn Decryptor>> {
|
||||
let subkey = hkdf_sha1(
|
||||
self.psk.as_ref(),
|
||||
salt,
|
||||
String::from("ss-subkey").as_bytes().to_vec(),
|
||||
self.key_size,
|
||||
)?;
|
||||
let unbound_key = UnboundKey::new(&self.algorithm, &subkey)
|
||||
.map_err(|_| anyhow!("new unbound key failed"))?;
|
||||
let nonce = IncSequence::new(NONCE_LEN);
|
||||
Ok(Box::new(AeadDecryptor(OpeningKey::new(unbound_key, nonce))))
|
||||
}
|
||||
}
|
||||
|
||||
const CRYPTO_ERROR: &str = "crypto error";
|
||||
|
||||
pub trait Encryptor: Sync + Send + Unpin {
|
||||
fn encrypt(&mut self, in_out: &mut BytesMut) -> Result<()>;
|
||||
fn tag_len(&self) -> usize;
|
||||
}
|
||||
|
||||
struct AeadEncryptor(SealingKey<IncSequence>);
|
||||
|
||||
impl Encryptor for AeadEncryptor {
|
||||
fn encrypt(&mut self, in_out: &mut BytesMut) -> Result<()> {
|
||||
self.0
|
||||
.seal_in_place_append_tag(Aad::empty(), in_out)
|
||||
.map_err(|_| anyhow!(CRYPTO_ERROR))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn tag_len(&self) -> usize {
|
||||
self.0.algorithm().tag_len()
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Decryptor: Sync + Send + Unpin {
|
||||
fn decrypt(&mut self, in_out: &mut BytesMut) -> Result<()>;
|
||||
fn tag_len(&self) -> usize;
|
||||
}
|
||||
|
||||
struct AeadDecryptor(OpeningKey<IncSequence>);
|
||||
|
||||
impl Decryptor for AeadDecryptor {
|
||||
fn decrypt(&mut self, in_out: &mut BytesMut) -> Result<()> {
|
||||
self.0
|
||||
.open_within(Aad::empty(), in_out, 0..)
|
||||
.map_err(|_| anyhow!(CRYPTO_ERROR))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn tag_len(&self) -> usize {
|
||||
self.0.algorithm().tag_len()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct IncSequence {
|
||||
counter: Vec<u8>,
|
||||
}
|
||||
|
||||
impl IncSequence {
|
||||
fn new(size: usize) -> Self {
|
||||
impl ShadowsocksNonceSequence {
|
||||
pub fn new(size: usize) -> Self {
|
||||
let mut c = Vec::new();
|
||||
for _ in 0..size {
|
||||
c.push(0xff);
|
||||
}
|
||||
IncSequence { counter: c }
|
||||
ShadowsocksNonceSequence(c)
|
||||
}
|
||||
|
||||
fn inc(&mut self) {
|
||||
for x in &mut self.counter {
|
||||
for x in &mut self.0 {
|
||||
*x = (*x).wrapping_add(1);
|
||||
if *x != 0 {
|
||||
return;
|
||||
@@ -203,14 +27,14 @@ impl IncSequence {
|
||||
}
|
||||
}
|
||||
|
||||
impl NonceSequence for IncSequence {
|
||||
fn advance(&mut self) -> Result<Nonce, Unspecified> {
|
||||
impl NonceSequence for ShadowsocksNonceSequence {
|
||||
fn advance(&mut self) -> Result<Vec<u8>> {
|
||||
self.inc();
|
||||
Nonce::try_assume_unique_for_key(&self.counter)
|
||||
Ok(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn kdf(pass: &str, size: usize) -> Result<Vec<u8>> {
|
||||
pub fn kdf(pass: &str, size: usize) -> Result<Vec<u8>> {
|
||||
let pass = pass.as_bytes();
|
||||
let mut key = Vec::new();
|
||||
let mut sum = Md5::digest(pass).to_vec();
|
||||
@@ -222,7 +46,7 @@ fn kdf(pass: &str, size: usize) -> Result<Vec<u8>> {
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
fn hkdf_sha1(key: &[u8], salt: &[u8], info: Vec<u8>, size: usize) -> Result<Vec<u8>> {
|
||||
pub fn hkdf_sha1(key: &[u8], salt: &[u8], info: Vec<u8>, size: usize) -> Result<Vec<u8>> {
|
||||
let (_, h) = Hkdf::<Sha1>::extract(Some(salt), key);
|
||||
let mut okm = vec![0u8; size];
|
||||
h.expand(&info, &mut okm)
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
mod crypto;
|
||||
mod shadow;
|
||||
|
||||
pub use crypto::{list_ciphers, AeadCipher, Cipher};
|
||||
pub use shadow::{
|
||||
ShadowedDatagram, ShadowedDatagramRecvHalf, ShadowedDatagramSendHalf, ShadowedStream,
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::{cmp::min, io, net::SocketAddr, pin::Pin, sync::Arc};
|
||||
|
||||
use anyhow::Result;
|
||||
use anyhow::{anyhow, Result};
|
||||
use byteorder::{BigEndian, ByteOrder};
|
||||
use bytes::{BufMut, BytesMut};
|
||||
use futures::{
|
||||
@@ -11,9 +11,14 @@ use log::*;
|
||||
use rand::{rngs::StdRng, Rng, SeedableRng};
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
|
||||
use super::crypto::{AeadCipher, Cipher, Decryptor, Encryptor};
|
||||
use crate::common::crypto::{
|
||||
aead::{AeadCipher, AeadDecryptor, AeadEncryptor},
|
||||
Cipher, Decryptor, Encryptor, SizedCipher,
|
||||
};
|
||||
use crate::proxy::{ProxyDatagram, ProxyDatagramRecvHalf, ProxyDatagramSendHalf};
|
||||
|
||||
use super::crypto::{hkdf_sha1, kdf, ShadowsocksNonceSequence};
|
||||
|
||||
enum ReadState {
|
||||
WaitingSalt,
|
||||
WaitingLength,
|
||||
@@ -30,9 +35,10 @@ enum WriteState {
|
||||
|
||||
pub struct ShadowedStream<T> {
|
||||
inner: T,
|
||||
cipher: Box<dyn Cipher>,
|
||||
enc: Option<Box<dyn Encryptor>>,
|
||||
dec: Option<Box<dyn Decryptor>>,
|
||||
cipher: AeadCipher,
|
||||
psk: Vec<u8>,
|
||||
enc: Option<AeadEncryptor<ShadowsocksNonceSequence>>,
|
||||
dec: Option<AeadDecryptor<ShadowsocksNonceSequence>>,
|
||||
read_buf: BytesMut,
|
||||
write_buf: BytesMut,
|
||||
read_state: ReadState,
|
||||
@@ -42,10 +48,12 @@ pub struct ShadowedStream<T> {
|
||||
|
||||
impl<T> ShadowedStream<T> {
|
||||
pub fn new(s: T, cipher: &String, password: &String) -> Result<Self> {
|
||||
let cipher = Box::new(AeadCipher::new(cipher, password)?);
|
||||
let cipher = AeadCipher::new(cipher)?;
|
||||
let psk = kdf(password, cipher.key_len())?;
|
||||
Ok(ShadowedStream {
|
||||
inner: s,
|
||||
cipher,
|
||||
psk,
|
||||
enc: None,
|
||||
dec: None,
|
||||
|
||||
@@ -64,7 +72,10 @@ trait ReadExt {
|
||||
fn poll_read_exact(&mut self, cx: &mut Context, size: usize) -> Poll<io::Result<()>>;
|
||||
}
|
||||
|
||||
impl<T: AsyncRead + Unpin> ReadExt for ShadowedStream<T> {
|
||||
impl<T> ReadExt for ShadowedStream<T>
|
||||
where
|
||||
T: AsyncRead + Unpin,
|
||||
{
|
||||
fn poll_read_exact(&mut self, cx: &mut Context, size: usize) -> Poll<io::Result<()>> {
|
||||
self.read_buf.reserve(size);
|
||||
unsafe { self.read_buf.set_len(size) };
|
||||
@@ -94,7 +105,10 @@ fn crypto_err() -> io::Error {
|
||||
io::Error::new(io::ErrorKind::Other, "crypto error")
|
||||
}
|
||||
|
||||
impl<T: AsyncRead + Unpin> AsyncRead for ShadowedStream<T> {
|
||||
impl<T> AsyncRead for ShadowedStream<T>
|
||||
where
|
||||
T: AsyncRead + Unpin,
|
||||
{
|
||||
fn poll_read(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context,
|
||||
@@ -104,11 +118,20 @@ impl<T: AsyncRead + Unpin> AsyncRead for ShadowedStream<T> {
|
||||
match self.read_state {
|
||||
ReadState::WaitingSalt => {
|
||||
// read salt and create decryptor
|
||||
let salt_size = self.cipher.salt_size();
|
||||
let salt_size = self.cipher.key_len();
|
||||
ready!(self.poll_read_exact(cx, salt_size))?;
|
||||
let key = hkdf_sha1(
|
||||
&self.psk,
|
||||
&self.read_buf[..salt_size],
|
||||
String::from("ss-subkey").as_bytes().to_vec(),
|
||||
self.cipher.key_len(),
|
||||
)
|
||||
.map_err(|_| crypto_err())?;
|
||||
let nonce =
|
||||
super::crypto::ShadowsocksNonceSequence::new(self.cipher.nonce_len());
|
||||
let dec = self
|
||||
.cipher
|
||||
.decryptor(&self.read_buf[..salt_size])
|
||||
.decryptor(&key, nonce)
|
||||
.map_err(|_| crypto_err())?;
|
||||
self.dec.replace(dec);
|
||||
self.read_buf.clear();
|
||||
@@ -157,7 +180,10 @@ impl<T: AsyncRead + Unpin> AsyncRead for ShadowedStream<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsyncWrite + Unpin> AsyncWrite for ShadowedStream<T> {
|
||||
impl<T> AsyncWrite for ShadowedStream<T>
|
||||
where
|
||||
T: AsyncWrite + Unpin,
|
||||
{
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context,
|
||||
@@ -167,17 +193,28 @@ impl<T: AsyncWrite + Unpin> AsyncWrite for ShadowedStream<T> {
|
||||
match self.write_state {
|
||||
WriteState::WaitingSalt => {
|
||||
// generate random salt and create encryptor
|
||||
let salt_size = self.cipher.salt_size();
|
||||
let salt_size = self.cipher.key_len();
|
||||
self.write_buf.reserve(salt_size);
|
||||
unsafe { self.write_buf.set_len(salt_size) };
|
||||
let mut rng = StdRng::from_entropy();
|
||||
for i in 0..salt_size {
|
||||
self.write_buf[i] = rng.gen();
|
||||
}
|
||||
|
||||
let key = hkdf_sha1(
|
||||
&self.psk,
|
||||
&self.write_buf[..salt_size],
|
||||
String::from("ss-subkey").as_bytes().to_vec(),
|
||||
self.cipher.key_len(),
|
||||
)
|
||||
.map_err(|_| crypto_err())?;
|
||||
let nonce =
|
||||
super::crypto::ShadowsocksNonceSequence::new(self.cipher.nonce_len());
|
||||
let enc = self
|
||||
.cipher
|
||||
.encryptor(&self.write_buf[..salt_size])
|
||||
.encryptor(&key, nonce)
|
||||
.map_err(|_| crypto_err())?;
|
||||
|
||||
self.enc.replace(enc);
|
||||
|
||||
// ready to write salt
|
||||
@@ -262,8 +299,8 @@ impl<T: AsyncWrite + Unpin> AsyncWrite for ShadowedStream<T> {
|
||||
}
|
||||
|
||||
struct InnerHalf {
|
||||
// server: SocketAddr,
|
||||
cipher: Box<dyn Cipher>,
|
||||
cipher: AeadCipher,
|
||||
psk: Vec<u8>,
|
||||
}
|
||||
|
||||
struct Half<T> {
|
||||
@@ -280,7 +317,7 @@ pub struct ShadowedDatagramRecvHalf(Half<Box<dyn ProxyDatagramRecvHalf>>);
|
||||
|
||||
impl ShadowedDatagramRecvHalf {
|
||||
pub async fn recv_from(&mut self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
|
||||
let salt_size = self.0.inner.cipher.salt_size();
|
||||
let salt_size = self.0.inner.cipher.key_len();
|
||||
let tag_len = self.0.inner.cipher.tag_len();
|
||||
let buffer_size = salt_size + /* addr::MAX_SOCKS_ADDR_SIZE + */ buf.len() + tag_len;
|
||||
|
||||
@@ -303,17 +340,25 @@ impl ShadowedDatagramRecvHalf {
|
||||
|
||||
// buffer: |ciphertext(addr+payload)|tag|
|
||||
|
||||
let key = hkdf_sha1(
|
||||
&self.0.inner.psk,
|
||||
&salt,
|
||||
String::from("ss-subkey").as_bytes().to_vec(),
|
||||
self.0.inner.cipher.key_len(),
|
||||
)
|
||||
.map_err(|_| crypto_err())?;
|
||||
let nonce = ShadowsocksNonceSequence::new(self.0.inner.cipher.nonce_len());
|
||||
let mut dec = self
|
||||
.0
|
||||
.inner
|
||||
.cipher
|
||||
.decryptor(&salt)
|
||||
.decryptor(&key, nonce)
|
||||
.map_err(|_| crypto_err())?;
|
||||
|
||||
if self.0.buffer.len() < tag_len {
|
||||
debug!("buffer size {}", self.0.buffer.len());
|
||||
return Err(short_packet());
|
||||
}
|
||||
debug_assert_eq!(tag_len, dec.tag_len());
|
||||
|
||||
dec.decrypt(&mut self.0.buffer).map_err(|_| crypto_err())?;
|
||||
|
||||
@@ -341,7 +386,7 @@ impl ShadowedDatagramSendHalf {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let salt_size = self.0.inner.cipher.salt_size();
|
||||
let salt_size = self.0.inner.cipher.key_len();
|
||||
let tag_len = self.0.inner.cipher.tag_len();
|
||||
let buffer_size = salt_size + /* target.size() + */ buf.len() + tag_len;
|
||||
|
||||
@@ -355,40 +400,29 @@ impl ShadowedDatagramSendHalf {
|
||||
self.0.buffer[i] = rng.gen();
|
||||
}
|
||||
|
||||
// buffer: |salt|
|
||||
|
||||
let key = hkdf_sha1(
|
||||
&self.0.inner.psk,
|
||||
&self.0.buffer[..salt_size],
|
||||
String::from("ss-subkey").as_bytes().to_vec(),
|
||||
self.0.inner.cipher.key_len(),
|
||||
)
|
||||
.map_err(|_| crypto_err())?;
|
||||
let nonce = ShadowsocksNonceSequence::new(self.0.inner.cipher.nonce_len());
|
||||
let mut enc = self
|
||||
.0
|
||||
.inner
|
||||
.cipher
|
||||
.encryptor(&self.0.buffer[..salt_size])
|
||||
.encryptor(&key, nonce)
|
||||
.map_err(|_| crypto_err())?;
|
||||
debug_assert_eq!(enc.tag_len(), tag_len);
|
||||
|
||||
let mut piece = self.0.buffer.split_off(salt_size);
|
||||
|
||||
// buffer: |salt|
|
||||
// piece: ||
|
||||
|
||||
// target.write_into(&mut piece)?;
|
||||
|
||||
// buffer: |salt|
|
||||
// piece: |addr|
|
||||
|
||||
piece.put_slice(buf);
|
||||
|
||||
// buffer: |salt|
|
||||
// piece: |addr+payload|
|
||||
|
||||
enc.encrypt(&mut piece).map_err(|_| crypto_err())?;
|
||||
|
||||
// buffer: |salt|
|
||||
// piece: |ciphertext(addr+payload)|tag|
|
||||
|
||||
self.0.buffer.unsplit(piece);
|
||||
|
||||
// buffer: |salt|ciphertext(addr+payload)|tag|
|
||||
|
||||
self.0.half.send_to(&self.0.buffer, addr).await?;
|
||||
Ok(buf.len())
|
||||
}
|
||||
@@ -396,24 +430,25 @@ impl ShadowedDatagramSendHalf {
|
||||
|
||||
pub struct ShadowedDatagram {
|
||||
inner: Box<dyn ProxyDatagram>,
|
||||
// server: SocketAddr,
|
||||
cipher: Box<dyn Cipher>,
|
||||
cipher: AeadCipher,
|
||||
psk: Vec<u8>,
|
||||
recv_buf: BytesMut,
|
||||
send_buf: BytesMut,
|
||||
}
|
||||
|
||||
impl ShadowedDatagram {
|
||||
pub fn new(
|
||||
socket: Box<dyn ProxyDatagram>,
|
||||
/* server: SocketAddr,*/ cipher: Box<dyn Cipher>,
|
||||
) -> Self {
|
||||
ShadowedDatagram {
|
||||
pub fn new(socket: Box<dyn ProxyDatagram>, cipher: &String, password: &String) -> Result<Self> {
|
||||
let cipher =
|
||||
AeadCipher::new(cipher).map_err(|e| anyhow!("new aead cipher failed: {}", e))?;
|
||||
let psk =
|
||||
kdf(password, cipher.key_len()).map_err(|e| anyhow!("derive key failed: {}", e))?;
|
||||
Ok(ShadowedDatagram {
|
||||
inner: socket,
|
||||
// server,
|
||||
cipher,
|
||||
psk,
|
||||
recv_buf: BytesMut::with_capacity(65507),
|
||||
send_buf: BytesMut::with_capacity(65507),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates a shadowed datagram with a given initial buffer size. This buffer size is
|
||||
@@ -421,24 +456,28 @@ impl ShadowedDatagram {
|
||||
/// (allocate extra memory when need) enough space each time sending or receiving packets.
|
||||
pub fn with_initial_buffer_size(
|
||||
socket: Box<dyn ProxyDatagram>,
|
||||
// server: SocketAddr,
|
||||
cipher: Box<dyn Cipher>,
|
||||
cipher: &String,
|
||||
password: &String,
|
||||
buf_size: usize,
|
||||
) -> Self {
|
||||
ShadowedDatagram {
|
||||
) -> Result<Self> {
|
||||
let cipher =
|
||||
AeadCipher::new(cipher).map_err(|e| anyhow!("new aead cipher failed: {}", e))?;
|
||||
let psk =
|
||||
kdf(password, cipher.key_len()).map_err(|e| anyhow!("derive key failed: {}", e))?;
|
||||
Ok(ShadowedDatagram {
|
||||
inner: socket,
|
||||
// server,
|
||||
cipher,
|
||||
psk,
|
||||
recv_buf: BytesMut::with_capacity(buf_size),
|
||||
send_buf: BytesMut::with_capacity(buf_size),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn split(self) -> (ShadowedDatagramRecvHalf, ShadowedDatagramSendHalf) {
|
||||
let (r, s) = self.inner.split();
|
||||
let hi = Arc::new(InnerHalf {
|
||||
// server: self.server,
|
||||
cipher: self.cipher,
|
||||
psk: self.psk,
|
||||
});
|
||||
(
|
||||
ShadowedDatagramRecvHalf(Half {
|
||||
|
||||
@@ -11,7 +11,6 @@ use bytes::{BufMut, BytesMut};
|
||||
use log::*;
|
||||
use tokio::net::UdpSocket;
|
||||
|
||||
use super::AeadCipher;
|
||||
use super::{ShadowedDatagram, ShadowedDatagramRecvHalf, ShadowedDatagramSendHalf};
|
||||
use crate::{
|
||||
common::dns_client::DnsClient,
|
||||
@@ -51,10 +50,6 @@ impl ProxyUdpHandler for Handler {
|
||||
datagram: Option<Box<dyn ProxyDatagram>>,
|
||||
_stream: Option<Box<dyn ProxyStream>>,
|
||||
) -> io::Result<Box<dyn ProxyDatagram>> {
|
||||
let cipher = AeadCipher::new(&self.cipher, &self.password).map_err(|e| {
|
||||
io::Error::new(io::ErrorKind::Other, format!("create cipher failed: {}", e))
|
||||
})?;
|
||||
|
||||
let ips = match self
|
||||
.dns_client
|
||||
.lookup_with_bind(String::from(&self.address), &self.bind_addr)
|
||||
@@ -84,7 +79,18 @@ impl ProxyUdpHandler for Handler {
|
||||
socket
|
||||
};
|
||||
|
||||
let dgram = ShadowedDatagram::with_initial_buffer_size(socket, Box::new(cipher), 2 * 1024);
|
||||
let dgram = ShadowedDatagram::with_initial_buffer_size(
|
||||
socket,
|
||||
&self.cipher,
|
||||
&self.password,
|
||||
2 * 1024,
|
||||
)
|
||||
.map_err(|e| {
|
||||
Error::new(
|
||||
ErrorKind::Other,
|
||||
format!("new shadowed stream failed: {}", e),
|
||||
)
|
||||
})?;
|
||||
let (r, s) = dgram.split();
|
||||
return Ok(Box::new(Datagram { r, s, server: addr }));
|
||||
}
|
||||
|
||||
@@ -1,73 +1,16 @@
|
||||
use std::io;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use futures::TryFutureExt;
|
||||
use log::*;
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tokio_rustls::{
|
||||
client::TlsStream, rustls, rustls::ClientConfig, webpki::DNSNameRef, TlsConnector,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
proxy::{ProxyStream, ProxyTcpHandler, SimpleStream},
|
||||
common::tls,
|
||||
proxy::{ProxyStream, ProxyTcpHandler},
|
||||
session::Session,
|
||||
};
|
||||
|
||||
struct InsecureVerifier;
|
||||
|
||||
impl rustls::ServerCertVerifier for InsecureVerifier {
|
||||
fn verify_server_cert(
|
||||
&self,
|
||||
_roots: &rustls::RootCertStore,
|
||||
_presented_certs: &[rustls::Certificate],
|
||||
_dns_name: DNSNameRef<'_>,
|
||||
_ocsp_response: &[u8],
|
||||
) -> Result<rustls::ServerCertVerified, rustls::TLSError> {
|
||||
Ok(rustls::ServerCertVerified::assertion())
|
||||
}
|
||||
}
|
||||
|
||||
async fn wrap_tls<S>(
|
||||
stream: S,
|
||||
domain: &str,
|
||||
alpns: Vec<String>,
|
||||
insecure: bool,
|
||||
) -> io::Result<TlsStream<S>>
|
||||
where
|
||||
S: AsyncRead + AsyncWrite + Unpin,
|
||||
{
|
||||
let mut config = ClientConfig::new();
|
||||
config
|
||||
.root_store
|
||||
.add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);
|
||||
|
||||
for alpn in alpns {
|
||||
config.alpn_protocols.push(alpn.as_bytes().to_vec());
|
||||
}
|
||||
|
||||
if insecure {
|
||||
let mut dangerous_config = config.dangerous();
|
||||
dangerous_config.set_certificate_verifier(Arc::new(InsecureVerifier));
|
||||
}
|
||||
|
||||
let config = TlsConnector::from(Arc::new(config));
|
||||
let dnsname = DNSNameRef::try_from_ascii_str(domain)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("invalid domain: {}", e)))?;
|
||||
let tls_stream = config
|
||||
.connect(dnsname, stream)
|
||||
.map_err(|e| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::Interrupted,
|
||||
format!("tls connect failed: {}", e),
|
||||
)
|
||||
})
|
||||
.await?;
|
||||
// FIXME check negotiated alpn
|
||||
Ok(tls_stream)
|
||||
}
|
||||
|
||||
pub struct Handler {
|
||||
pub server_name: String,
|
||||
pub alpns: Vec<String>,
|
||||
@@ -97,8 +40,12 @@ impl ProxyTcpHandler for Handler {
|
||||
trace!("wrapping tls with name {}", &name);
|
||||
match stream {
|
||||
Some(stream) => {
|
||||
let tls_stream = wrap_tls(stream, &name, self.alpns.clone(), false).await?;
|
||||
return Ok(Box::new(SimpleStream(tls_stream)));
|
||||
let tls_stream = tls::wrapper::wrap_tls(stream, &name, self.alpns.clone())
|
||||
.map_err(|e| {
|
||||
io::Error::new(io::ErrorKind::Other, format!("wrap tls failed: {}", e))
|
||||
})
|
||||
.await?;
|
||||
return Ok(tls_stream);
|
||||
}
|
||||
None => Err(io::Error::new(io::ErrorKind::Other, "invalid tls input")),
|
||||
}
|
||||
|
||||
@@ -34,10 +34,20 @@ pub fn new(
|
||||
let mut cfg = tun::Configuration::default();
|
||||
cfg.name(settings.name)
|
||||
.address(settings.address)
|
||||
.netmask(settings.netmask)
|
||||
.destination(settings.gateway)
|
||||
.mtu(settings.mtu)
|
||||
.up();
|
||||
.mtu(settings.mtu);
|
||||
|
||||
#[cfg(not(any(
|
||||
target_arch = "mips",
|
||||
target_arch = "mips64",
|
||||
target_arch = "mipsel",
|
||||
target_arch = "mipsel64",
|
||||
)))]
|
||||
{
|
||||
cfg.netmask(settings.netmask);
|
||||
}
|
||||
|
||||
cfg.up();
|
||||
cfg
|
||||
};
|
||||
|
||||
|
||||
Submodule leaf/src/proxy/tun/netstack/lwip updated: d20eaab2f6...b72244cc5d.
@@ -0,0 +1,138 @@
|
||||
use std::io::Read;
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
use byteorder::{BigEndian, ByteOrder};
|
||||
use digest::ExtendableOutputDirty;
|
||||
use log::*;
|
||||
use md5::{Digest, Md5};
|
||||
use sha3::Shake128;
|
||||
|
||||
use crate::common::crypto::{
|
||||
aead::{AeadCipher, AeadDecryptor, AeadEncryptor},
|
||||
Cipher, NonceSequence, SizedCipher,
|
||||
};
|
||||
|
||||
pub fn generate_chacha20poly1305_key(key: &[u8]) -> Vec<u8> {
|
||||
let key_1 = Md5::digest(&key).to_vec();
|
||||
let key_2 = Md5::digest(&key_1).to_vec();
|
||||
[key_1, key_2].concat()
|
||||
}
|
||||
|
||||
pub fn new_encryptor(
|
||||
cipher: &str,
|
||||
key: &[u8],
|
||||
iv: &[u8],
|
||||
) -> Result<AeadEncryptor<VMessAEADSequence>> {
|
||||
let aead_cipher = AeadCipher::new(cipher)?;
|
||||
let key = match cipher.to_lowercase().as_str() {
|
||||
"chacha20-poly1305" | "chacha20-ietf-poly1305" => generate_chacha20poly1305_key(key),
|
||||
"aes-128-gcm" => key.to_vec(),
|
||||
_ => return Err(anyhow!("unsupported cipher: {}", cipher)),
|
||||
};
|
||||
let nonce = VMessAEADSequence::new(iv.to_vec(), aead_cipher.nonce_len());
|
||||
let enc = aead_cipher.encryptor(&key, nonce)?;
|
||||
Ok(enc)
|
||||
}
|
||||
|
||||
pub fn new_decryptor(
|
||||
cipher: &str,
|
||||
key: &[u8],
|
||||
iv: &[u8],
|
||||
) -> Result<AeadDecryptor<VMessAEADSequence>> {
|
||||
let aead_cipher = AeadCipher::new(cipher)?;
|
||||
let key = match cipher.to_lowercase().as_str() {
|
||||
"chacha20-poly1305" | "chacha20-ietf-poly1305" => generate_chacha20poly1305_key(key),
|
||||
"aes-128-gcm" => key.to_vec(),
|
||||
_ => return Err(anyhow!("unsupported cipher: {}", cipher)),
|
||||
};
|
||||
let nonce = VMessAEADSequence::new(iv.to_vec(), aead_cipher.nonce_len());
|
||||
let dec = aead_cipher.decryptor(&key, nonce)?;
|
||||
Ok(dec)
|
||||
}
|
||||
|
||||
pub struct VMessAEADSequence {
|
||||
nonce: Vec<u8>,
|
||||
size: usize,
|
||||
count: u16,
|
||||
}
|
||||
|
||||
impl VMessAEADSequence {
|
||||
pub fn new(nonce: Vec<u8>, size: usize) -> Self {
|
||||
assert_eq!(nonce.len() >= size, true);
|
||||
VMessAEADSequence {
|
||||
nonce,
|
||||
size,
|
||||
count: 0xffff,
|
||||
}
|
||||
}
|
||||
|
||||
fn inc(&mut self) {
|
||||
self.count = self.count.wrapping_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
impl NonceSequence for VMessAEADSequence {
|
||||
fn advance(&mut self) -> Result<Vec<u8>> {
|
||||
self.inc();
|
||||
BigEndian::write_u16(&mut self.nonce, self.count);
|
||||
Ok(self.nonce[..self.size].to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ShakeSizeParser {
|
||||
shake_reader: sha3::Sha3XofReader,
|
||||
buf: [u8; 2],
|
||||
}
|
||||
|
||||
impl ShakeSizeParser {
|
||||
pub fn new(nonce: &[u8]) -> Self {
|
||||
let mut shake = Shake128::default();
|
||||
digest::Update::update(&mut shake, nonce);
|
||||
let shake_reader = shake.finalize_xof_dirty();
|
||||
ShakeSizeParser {
|
||||
shake_reader,
|
||||
buf: [0, 0],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn size_bytes(&self) -> usize {
|
||||
2
|
||||
}
|
||||
|
||||
fn next(&mut self) -> u16 {
|
||||
match self.shake_reader.read(&mut self.buf) {
|
||||
Ok(_) => (),
|
||||
Err(e) => {
|
||||
error!("read from shake reader failed: {}", e);
|
||||
}
|
||||
};
|
||||
BigEndian::read_u16(&self.buf)
|
||||
}
|
||||
|
||||
pub fn decode(&mut self, b: &[u8]) -> u16 {
|
||||
assert_eq!(b.len() >= 2, true);
|
||||
let mask = self.next();
|
||||
let size = BigEndian::read_u16(b);
|
||||
mask ^ size
|
||||
}
|
||||
|
||||
pub fn encode(&mut self, size: u16, b: &mut [u8]) {
|
||||
let mask = self.next();
|
||||
BigEndian::write_u16(b, mask ^ size);
|
||||
}
|
||||
}
|
||||
|
||||
pub trait PaddingLengthGenerator {
|
||||
fn next_padding_len(&mut self) -> u16;
|
||||
fn max_padding_len(&self) -> u16;
|
||||
}
|
||||
|
||||
impl PaddingLengthGenerator for ShakeSizeParser {
|
||||
fn next_padding_len(&mut self) -> u16 {
|
||||
self.next() % 64
|
||||
}
|
||||
|
||||
fn max_padding_len(&self) -> u16 {
|
||||
64
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
mod crypto;
|
||||
mod vmess;
|
||||
pub use vmess::*;
|
||||
|
||||
pub mod tcp;
|
||||
pub mod udp;
|
||||
|
||||
@@ -11,7 +11,9 @@ use crate::{
|
||||
session::Session,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
use super::crypto::*;
|
||||
use super::vmess;
|
||||
use super::vmess::*;
|
||||
|
||||
pub struct Handler {
|
||||
pub address: String,
|
||||
@@ -51,6 +53,21 @@ impl ProxyTcpHandler for Handler {
|
||||
request_header.set_option(vmess::REQUEST_OPTION_CHUNK_MASKING);
|
||||
request_header.set_option(vmess::REQUEST_OPTION_GLOBAL_PADDING);
|
||||
|
||||
match self.security.to_lowercase().as_str() {
|
||||
"chacha20-poly1305" | "chacha20-ietf-poly1305" => {
|
||||
request_header.security = vmess::SECURITY_TYPE_CHACHA20_POLY1305;
|
||||
}
|
||||
"aes-128-gcm" => {
|
||||
request_header.security = vmess::SECURITY_TYPE_AES128_GCM;
|
||||
}
|
||||
_ => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("unsupported cipher: {}", &self.security),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
let mut header_buf = BytesMut::new();
|
||||
let client_sess = ClientSession::new();
|
||||
request_header
|
||||
@@ -63,7 +80,8 @@ impl ProxyTcpHandler for Handler {
|
||||
})?;
|
||||
|
||||
let enc_size_parser = ShakeSizeParser::new(&client_sess.request_body_iv);
|
||||
let enc = vmess::new_encryptor(
|
||||
|
||||
let enc = new_encryptor(
|
||||
self.security.as_str(),
|
||||
&client_sess.request_body_key,
|
||||
&client_sess.request_body_iv,
|
||||
@@ -73,7 +91,7 @@ impl ProxyTcpHandler for Handler {
|
||||
})?;
|
||||
|
||||
let dec_size_parser = ShakeSizeParser::new(&client_sess.response_body_iv);
|
||||
let dec = vmess::new_decryptor(
|
||||
let dec = new_decryptor(
|
||||
self.security.as_str(),
|
||||
&client_sess.response_body_key,
|
||||
&client_sess.response_body_iv,
|
||||
@@ -102,6 +120,7 @@ impl ProxyTcpHandler for Handler {
|
||||
enc_size_parser,
|
||||
dec,
|
||||
dec_size_parser,
|
||||
16, // FIXME
|
||||
);
|
||||
Ok(Box::new(SimpleStream(stream)))
|
||||
}
|
||||
|
||||
@@ -16,7 +16,9 @@ use crate::{
|
||||
session::{Session, SocksAddr},
|
||||
};
|
||||
|
||||
use super::*;
|
||||
use super::crypto::*;
|
||||
use super::vmess;
|
||||
use super::vmess::*;
|
||||
|
||||
pub struct Handler {
|
||||
pub address: String,
|
||||
@@ -61,6 +63,21 @@ impl ProxyUdpHandler for Handler {
|
||||
request_header.set_option(vmess::REQUEST_OPTION_CHUNK_MASKING);
|
||||
request_header.set_option(vmess::REQUEST_OPTION_GLOBAL_PADDING);
|
||||
|
||||
match self.security.to_lowercase().as_str() {
|
||||
"chacha20-poly1305" | "chacha20-ietf-poly1305" => {
|
||||
request_header.security = vmess::SECURITY_TYPE_CHACHA20_POLY1305;
|
||||
}
|
||||
"aes-128-gcm" => {
|
||||
request_header.security = vmess::SECURITY_TYPE_AES128_GCM;
|
||||
}
|
||||
_ => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("unsupported cipher: {}", &self.security),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
let mut header_buf = BytesMut::new();
|
||||
let client_sess = ClientSession::new();
|
||||
request_header
|
||||
@@ -73,7 +90,7 @@ impl ProxyUdpHandler for Handler {
|
||||
})?;
|
||||
|
||||
let enc_size_parser = ShakeSizeParser::new(&client_sess.request_body_iv);
|
||||
let enc = vmess::new_encryptor(
|
||||
let enc = new_encryptor(
|
||||
self.security.as_str(),
|
||||
&client_sess.request_body_key,
|
||||
&client_sess.request_body_iv,
|
||||
@@ -83,7 +100,7 @@ impl ProxyUdpHandler for Handler {
|
||||
})?;
|
||||
|
||||
let dec_size_parser = ShakeSizeParser::new(&client_sess.response_body_iv);
|
||||
let dec = vmess::new_decryptor(
|
||||
let dec = new_decryptor(
|
||||
self.security.as_str(),
|
||||
&client_sess.response_body_key,
|
||||
&client_sess.response_body_iv,
|
||||
@@ -112,6 +129,7 @@ impl ProxyUdpHandler for Handler {
|
||||
enc_size_parser,
|
||||
dec,
|
||||
dec_size_parser,
|
||||
16, // FIXME
|
||||
);
|
||||
Ok(Box::new(Datagram {
|
||||
stream,
|
||||
|
||||
+21
-154
@@ -1,34 +1,31 @@
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use std::{cmp::min, io, io::Read, pin::Pin};
|
||||
use std::{cmp::min, io, pin::Pin};
|
||||
|
||||
use aes::Aes128;
|
||||
use anyhow::anyhow;
|
||||
use anyhow::Result;
|
||||
use byteorder::{BigEndian, ByteOrder};
|
||||
use bytes::{BufMut, BytesMut};
|
||||
use cfb_mode::stream_cipher::{NewStreamCipher, StreamCipher};
|
||||
use cfb_mode::Cfb;
|
||||
use digest::ExtendableOutputDirty;
|
||||
use futures::{
|
||||
ready,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
use hmac::{Hmac, Mac, NewMac};
|
||||
use log::*;
|
||||
use lz_fnv::{Fnv1a, FnvHasher};
|
||||
use md5::{Digest, Md5};
|
||||
use rand::{rngs::StdRng, Rng, SeedableRng};
|
||||
use ring::{
|
||||
aead::{Aad, BoundKey, Nonce, NonceSequence, OpeningKey, SealingKey, UnboundKey, NONCE_LEN},
|
||||
error::Unspecified,
|
||||
};
|
||||
use sha3::Shake128;
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::common;
|
||||
use crate::common::crypto::{
|
||||
aead::{AeadDecryptor, AeadEncryptor},
|
||||
Decryptor, Encryptor,
|
||||
};
|
||||
use crate::session::{SocksAddr, SocksAddrWireType};
|
||||
|
||||
use super::crypto::{PaddingLengthGenerator, ShakeSizeParser, VMessAEADSequence};
|
||||
|
||||
type RequestCommand = u8;
|
||||
|
||||
pub const REQUEST_COMMAND_TCP: RequestCommand = 0x01;
|
||||
@@ -177,133 +174,6 @@ impl ClientSession {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct VMessAEADSequence {
|
||||
nonce: Vec<u8>,
|
||||
size: usize,
|
||||
count: u16,
|
||||
}
|
||||
|
||||
impl VMessAEADSequence {
|
||||
pub fn new(nonce: Vec<u8>, size: usize) -> Self {
|
||||
assert_eq!(nonce.len() >= size, true);
|
||||
VMessAEADSequence {
|
||||
nonce,
|
||||
size,
|
||||
count: 0xffff,
|
||||
}
|
||||
}
|
||||
|
||||
fn inc(&mut self) {
|
||||
self.count = self.count.wrapping_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
impl NonceSequence for VMessAEADSequence {
|
||||
fn advance(&mut self) -> Result<Nonce, Unspecified> {
|
||||
self.inc();
|
||||
BigEndian::write_u16(&mut self.nonce, self.count);
|
||||
Nonce::try_assume_unique_for_key(&self.nonce[..self.size])
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ShakeSizeParser {
|
||||
shake_reader: sha3::Sha3XofReader,
|
||||
buf: [u8; 2],
|
||||
}
|
||||
|
||||
impl ShakeSizeParser {
|
||||
pub fn new(nonce: &[u8]) -> Self {
|
||||
let mut shake = Shake128::default();
|
||||
digest::Update::update(&mut shake, nonce);
|
||||
let shake_reader = shake.finalize_xof_dirty();
|
||||
ShakeSizeParser {
|
||||
shake_reader,
|
||||
buf: [0, 0],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn size_bytes(&self) -> usize {
|
||||
2
|
||||
}
|
||||
|
||||
fn next(&mut self) -> u16 {
|
||||
match self.shake_reader.read(&mut self.buf) {
|
||||
Ok(_) => (),
|
||||
Err(e) => {
|
||||
error!("read from shake reader failed: {}", e);
|
||||
}
|
||||
};
|
||||
BigEndian::read_u16(&self.buf)
|
||||
}
|
||||
|
||||
pub fn decode(&mut self, b: &[u8]) -> u16 {
|
||||
assert_eq!(b.len() >= 2, true);
|
||||
let mask = self.next();
|
||||
let size = BigEndian::read_u16(b);
|
||||
mask ^ size
|
||||
}
|
||||
|
||||
pub fn encode(&mut self, size: u16, b: &mut [u8]) {
|
||||
let mask = self.next();
|
||||
BigEndian::write_u16(b, mask ^ size);
|
||||
}
|
||||
}
|
||||
|
||||
pub trait PaddingLengthGenerator {
|
||||
fn next_padding_len(&mut self) -> u16;
|
||||
fn max_padding_len(&self) -> u16;
|
||||
}
|
||||
|
||||
impl PaddingLengthGenerator for ShakeSizeParser {
|
||||
fn next_padding_len(&mut self) -> u16 {
|
||||
self.next() % 64
|
||||
}
|
||||
|
||||
fn max_padding_len(&self) -> u16 {
|
||||
64
|
||||
}
|
||||
}
|
||||
|
||||
fn generate_chacha20poly1305_key(key: &[u8]) -> Vec<u8> {
|
||||
let key_1 = Md5::digest(&key).to_vec();
|
||||
let key_2 = Md5::digest(&key_1).to_vec();
|
||||
[key_1, key_2].concat()
|
||||
}
|
||||
|
||||
pub fn new_encryptor(cipher: &str, key: &[u8], iv: &[u8]) -> Result<SealingKey<VMessAEADSequence>> {
|
||||
let key = generate_chacha20poly1305_key(key);
|
||||
let nonce = VMessAEADSequence::new(iv.to_vec(), NONCE_LEN);
|
||||
let unbound_key = if let Some(cipher) = common::crypto::AEAD_LIST.get(cipher) {
|
||||
let key = match UnboundKey::new(cipher, &key) {
|
||||
Ok(k) => k,
|
||||
Err(e) => {
|
||||
return Err(anyhow!(format!("new unbound key failed: {}", e)));
|
||||
}
|
||||
};
|
||||
key
|
||||
} else {
|
||||
return Err(anyhow!(format!("invalid cipher {}", cipher)));
|
||||
};
|
||||
Ok(SealingKey::new(unbound_key, nonce))
|
||||
}
|
||||
|
||||
pub fn new_decryptor(cipher: &str, key: &[u8], iv: &[u8]) -> Result<OpeningKey<VMessAEADSequence>> {
|
||||
let key = generate_chacha20poly1305_key(key);
|
||||
let nonce = VMessAEADSequence::new(iv.to_vec(), NONCE_LEN);
|
||||
let unbound_key = if let Some(cipher) = common::crypto::AEAD_LIST.get(cipher) {
|
||||
let key = match UnboundKey::new(cipher, &key) {
|
||||
Ok(k) => k,
|
||||
Err(e) => {
|
||||
return Err(anyhow!(format!("new unbound key failed: {}", e)));
|
||||
}
|
||||
};
|
||||
key
|
||||
} else {
|
||||
return Err(anyhow!(format!("invalid cipher {}", cipher)));
|
||||
};
|
||||
Ok(OpeningKey::new(unbound_key, nonce))
|
||||
}
|
||||
|
||||
enum ReadState {
|
||||
WaitingResponseHeader,
|
||||
WaitingLength,
|
||||
@@ -319,10 +189,11 @@ enum WriteState {
|
||||
pub struct VMessAuthStream<T> {
|
||||
inner: T,
|
||||
sess: ClientSession,
|
||||
enc: SealingKey<VMessAEADSequence>,
|
||||
enc: AeadEncryptor<VMessAEADSequence>,
|
||||
enc_size_parser: ShakeSizeParser,
|
||||
dec: OpeningKey<VMessAEADSequence>,
|
||||
dec: AeadDecryptor<VMessAEADSequence>,
|
||||
dec_size_parser: ShakeSizeParser,
|
||||
tag_len: usize,
|
||||
read_buf: BytesMut,
|
||||
write_buf: BytesMut,
|
||||
read_state: ReadState,
|
||||
@@ -334,10 +205,11 @@ impl<T> VMessAuthStream<T> {
|
||||
pub fn new(
|
||||
s: T,
|
||||
sess: ClientSession,
|
||||
enc: SealingKey<VMessAEADSequence>,
|
||||
enc: AeadEncryptor<VMessAEADSequence>,
|
||||
enc_size_parser: ShakeSizeParser,
|
||||
dec: OpeningKey<VMessAEADSequence>,
|
||||
dec: AeadDecryptor<VMessAEADSequence>,
|
||||
dec_size_parser: ShakeSizeParser,
|
||||
tag_len: usize,
|
||||
) -> Self {
|
||||
VMessAuthStream {
|
||||
inner: s,
|
||||
@@ -346,6 +218,7 @@ impl<T> VMessAuthStream<T> {
|
||||
enc_size_parser,
|
||||
dec,
|
||||
dec_size_parser,
|
||||
tag_len,
|
||||
|
||||
// never depend on these sizes, reserve when need
|
||||
read_buf: BytesMut::with_capacity(0x2 + 0x4000),
|
||||
@@ -434,13 +307,10 @@ impl<T: AsyncRead + Unpin> AsyncRead for VMessAuthStream<T> {
|
||||
ready!(me.poll_read_exact(cx, size))?;
|
||||
let encrypted_size = size - padding_size;
|
||||
let _ = me.read_buf.split_off(encrypted_size); // trim padding
|
||||
me.dec
|
||||
.open_within(Aad::empty(), &mut me.read_buf, 0..)
|
||||
.map_err(|_| crypto_err())?;
|
||||
me.dec.decrypt(&mut me.read_buf).map_err(|_| crypto_err())?;
|
||||
|
||||
// ready to read plaintext payload into buf
|
||||
me.read_state =
|
||||
ReadState::PendingData(encrypted_size - me.dec.algorithm().tag_len());
|
||||
me.read_state = ReadState::PendingData(encrypted_size - me.tag_len);
|
||||
}
|
||||
ReadState::PendingData(n) => {
|
||||
let to_read = min(buf.len(), n);
|
||||
@@ -471,11 +341,10 @@ impl<T: AsyncWrite + Unpin> AsyncWrite for VMessAuthStream<T> {
|
||||
match self.write_state {
|
||||
WriteState::WaitingChunk => {
|
||||
let me = &mut *self;
|
||||
let tag_len = me.enc.algorithm().tag_len();
|
||||
let padding_size = me.enc_size_parser.next_padding_len() as usize;
|
||||
let max_payload_size = 0x4000 - tag_len - padding_size;
|
||||
let max_payload_size = 0x4000 - me.tag_len - padding_size;
|
||||
let consume_len = min(buf.len(), max_payload_size);
|
||||
let payload_len = consume_len + tag_len + padding_size;
|
||||
let payload_len = consume_len + me.tag_len + padding_size;
|
||||
|
||||
// encode size
|
||||
let size_bytes = me.enc_size_parser.size_bytes();
|
||||
@@ -486,13 +355,11 @@ impl<T: AsyncWrite + Unpin> AsyncWrite for VMessAuthStream<T> {
|
||||
let mut piece2 = me.write_buf.split_off(size_bytes);
|
||||
|
||||
// seal payload
|
||||
piece2.reserve(consume_len + tag_len);
|
||||
piece2.reserve(consume_len + me.tag_len);
|
||||
piece2.put_slice(&buf[..consume_len]);
|
||||
me.enc
|
||||
.seal_in_place_append_tag(Aad::empty(), &mut piece2)
|
||||
.map_err(|_| crypto_err())?;
|
||||
me.enc.encrypt(&mut piece2).map_err(|_| crypto_err())?;
|
||||
|
||||
let mut piece3 = piece2.split_off(consume_len + tag_len);
|
||||
let mut piece3 = piece2.split_off(consume_len + me.tag_len);
|
||||
|
||||
// add random paddings
|
||||
if padding_size > 0 {
|
||||
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
target=$1
|
||||
|
||||
if [[ "$target" == *"mips"* ]]; then
|
||||
cross build --release --target $target --manifest-path leaf-bin/Cargo.toml --no-default-features --features "common config openssl-aead openssl-tls"
|
||||
else
|
||||
cross build --release --target $target --manifest-path leaf-bin/Cargo.toml --no-default-features --features "common config ring-aead rustls-tls"
|
||||
fi
|
||||
Reference in new issue
Block a user