From ce5366ebc4c15e83101f6caf5ff3aba9cccb2026 Mon Sep 17 00:00:00 2001 From: eric Date: Sat, 24 Oct 2020 10:57:59 +0800 Subject: [PATCH] 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. --- .github/workflows/build.yml | 59 ++-- .github/workflows/release.yml | 97 +++---- Makefile | 4 +- leaf-bin/Cargo.toml | 21 +- leaf-bin/src/main.rs | 7 - leaf/Cargo.toml | 21 +- leaf/src/app/dispatcher.rs | 12 +- leaf/src/common/crypto.rs | 402 ++++++++++++++++++++++++++- leaf/src/common/mod.rs | 1 + leaf/src/common/tls.rs | 126 +++++++++ leaf/src/proxy/shadowsocks/crypto.rs | 198 +------------ leaf/src/proxy/shadowsocks/mod.rs | 1 - leaf/src/proxy/shadowsocks/shadow.rs | 149 ++++++---- leaf/src/proxy/shadowsocks/udp.rs | 18 +- leaf/src/proxy/tls/tcp.rs | 69 +---- leaf/src/proxy/tun/inbound.rs | 16 +- leaf/src/proxy/tun/netstack/lwip | 2 +- leaf/src/proxy/vmess/crypto.rs | 138 +++++++++ leaf/src/proxy/vmess/mod.rs | 2 +- leaf/src/proxy/vmess/tcp.rs | 25 +- leaf/src/proxy/vmess/udp.rs | 24 +- leaf/src/proxy/vmess/vmess.rs | 175 ++---------- misc/build_cross.sh | 9 + 23 files changed, 986 insertions(+), 590 deletions(-) create mode 100644 leaf/src/common/tls.rs create mode 100644 leaf/src/proxy/vmess/crypto.rs create mode 100755 misc/build_cross.sh diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 76b1f4a..d8a15f2 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -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: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1ce638f..cb9006f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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 diff --git a/Makefile b/Makefile index 8547c1d..115cb9e 100644 --- a/Makefile +++ b/Makefile @@ -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 diff --git a/leaf-bin/Cargo.toml b/leaf-bin/Cargo.toml index e15eb7a..1314876 100644 --- a/leaf-bin/Cargo.toml +++ b/leaf-bin/Cargo.toml @@ -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" diff --git a/leaf-bin/src/main.rs b/leaf-bin/src/main.rs index b9e1dd6..7a81e31 100644 --- a/leaf-bin/src/main.rs +++ b/leaf-bin/src/main.rs @@ -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::*; diff --git a/leaf/Cargo.toml b/leaf/Cargo.toml index e06b3a8..4581dea 100644 --- a/leaf/Cargo.toml +++ b/leaf/Cargo.toml @@ -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" diff --git a/leaf/src/app/dispatcher.rs b/leaf/src/app/dispatcher.rs index fdc6a6d..2725cb0 100644 --- a/leaf/src/app/dispatcher.rs +++ b/leaf/src/app/dispatcher.rs @@ -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, diff --git a/leaf/src/common/crypto.rs b/leaf/src/common/crypto.rs index f206f6b..b8d2ecd 100644 --- a/leaf/src/common/crypto.rs +++ b/leaf/src/common/crypto.rs @@ -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: Sync + Send + Unpin +where + N: NonceSequence, +{ + type Enc; + type Dec; + + fn encryptor(&self, key: &[u8], nonce: N) -> Result; + fn decryptor(&self, key: &[u8], nonce: N) -> Result; +} + +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(&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(&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>; +} + +#[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 { + let alg = match AEAD_LIST.get(cipher) { + Some(v) => v, + None => return Err(anyhow!("unsupported cipher: {}", cipher)), + }; + Ok(AeadCipher { cipher: *alg }) + } + } + + impl Cipher for AeadCipher + where + N: 'static + NonceSequence, + { + type Enc = AeadEncryptor; + type Dec = AeadDecryptor; + + fn encryptor(&self, key: &[u8], nonce: N) -> Result { + Ok(AeadEncryptor::new( + self.cipher, + key.to_vec(), + nonce, + self.tag_len(), + )) + } + + fn decryptor(&self, key: &[u8], nonce: N) -> Result { + 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 { + cipher: symm::Cipher, + key: Vec, + nonce: N, + tag_len: usize, + } + + impl AeadEncryptor + where + N: NonceSequence, + { + pub fn new(cipher: symm::Cipher, key: Vec, nonce: N, tag_len: usize) -> Self { + AeadEncryptor { + cipher, + key, + nonce, + tag_len, + } + } + } + + impl Encryptor for AeadEncryptor + where + N: NonceSequence, + { + fn encrypt(&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 { + cipher: symm::Cipher, + key: Vec, + nonce: N, + tag_len: usize, + } + + impl AeadDecryptor + where + N: NonceSequence, + { + pub fn new(cipher: symm::Cipher, key: Vec, nonce: N, tag_len: usize) -> Self { + AeadDecryptor { + cipher, + key, + nonce, + tag_len, + } + } + } + + impl Decryptor for AeadDecryptor + where + N: NonceSequence, + { + fn decrypt(&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 { + let alg = match AEAD_LIST.get(cipher) { + Some(v) => v, + None => return Err(anyhow!("unsupported cipher: {}", cipher)), + }; + Ok(AeadCipher { algorithm: alg }) + } + } + + impl Cipher for AeadCipher + where + N: 'static + NonceSequence, + { + type Enc = AeadEncryptor; + type Dec = AeadDecryptor; + + fn encryptor(&self, key: &[u8], nonce: N) -> Result { + 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 { + 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 { + enc: LessSafeKey, + nonce: N, + } + + impl AeadEncryptor + where + N: NonceSequence, + { + pub fn new(enc: LessSafeKey, nonce: N) -> Self { + AeadEncryptor { enc, nonce } + } + } + + impl Encryptor for AeadEncryptor + where + N: NonceSequence, + { + fn encrypt(&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 { + enc: LessSafeKey, + nonce: N, + } + + impl AeadDecryptor + where + N: NonceSequence, + { + pub fn new(enc: LessSafeKey, nonce: N) -> Self { + AeadDecryptor { enc, nonce } + } + } + + impl Decryptor for AeadDecryptor + where + N: NonceSequence, + { + fn decrypt(&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); + + 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> { + 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); + } } diff --git a/leaf/src/common/mod.rs b/leaf/src/common/mod.rs index 99c5ef7..c66e61d 100644 --- a/leaf/src/common/mod.rs +++ b/leaf/src/common/mod.rs @@ -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; diff --git a/leaf/src/common/tls.rs b/leaf/src/common/tls.rs new file mode 100644 index 0000000..ed71efd --- /dev/null +++ b/leaf/src/common/tls.rs @@ -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 { + // Ok(rustls::ServerCertVerified::assertion()) + // } + // } + + pub async fn wrap_tls( + stream: S, + domain: &str, + alpns: Vec, + // insecure: bool, + ) -> Result> + 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( + stream: S, + domain: &str, + alpns: Vec, + // insecure: bool, + ) -> Result> + 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::>>() + .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::>>() + .concat(); + assert_eq!(wire, expected); + } +} diff --git a/leaf/src/proxy/shadowsocks/crypto.rs b/leaf/src/proxy/shadowsocks/crypto.rs index 77fcd32..fcdd473 100644 --- a/leaf/src/proxy/shadowsocks/crypto.rs +++ b/leaf/src/proxy/shadowsocks/crypto.rs @@ -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); -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>; - fn decryptor(&self, salt: &[u8]) -> Result>; -} - -pub struct AeadCipher { - psk: Bytes, - key_size: usize, - salt_size: usize, - algorithm: &'static Algorithm, -} - -impl AeadCipher { - pub fn new(cipher: &str, password: &str) -> Result { - 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> { - 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> { - 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); - -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); - -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, -} - -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 { +impl NonceSequence for ShadowsocksNonceSequence { + fn advance(&mut self) -> Result> { self.inc(); - Nonce::try_assume_unique_for_key(&self.counter) + Ok(self.0.clone()) } } -fn kdf(pass: &str, size: usize) -> Result> { +pub fn kdf(pass: &str, size: usize) -> Result> { 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> { Ok(key) } -fn hkdf_sha1(key: &[u8], salt: &[u8], info: Vec, size: usize) -> Result> { +pub fn hkdf_sha1(key: &[u8], salt: &[u8], info: Vec, size: usize) -> Result> { let (_, h) = Hkdf::::extract(Some(salt), key); let mut okm = vec![0u8; size]; h.expand(&info, &mut okm) diff --git a/leaf/src/proxy/shadowsocks/mod.rs b/leaf/src/proxy/shadowsocks/mod.rs index b2d4294..3361441 100644 --- a/leaf/src/proxy/shadowsocks/mod.rs +++ b/leaf/src/proxy/shadowsocks/mod.rs @@ -1,7 +1,6 @@ mod crypto; mod shadow; -pub use crypto::{list_ciphers, AeadCipher, Cipher}; pub use shadow::{ ShadowedDatagram, ShadowedDatagramRecvHalf, ShadowedDatagramSendHalf, ShadowedStream, }; diff --git a/leaf/src/proxy/shadowsocks/shadow.rs b/leaf/src/proxy/shadowsocks/shadow.rs index b28c8c5..97e731e 100644 --- a/leaf/src/proxy/shadowsocks/shadow.rs +++ b/leaf/src/proxy/shadowsocks/shadow.rs @@ -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 { inner: T, - cipher: Box, - enc: Option>, - dec: Option>, + cipher: AeadCipher, + psk: Vec, + enc: Option>, + dec: Option>, read_buf: BytesMut, write_buf: BytesMut, read_state: ReadState, @@ -42,10 +48,12 @@ pub struct ShadowedStream { impl ShadowedStream { pub fn new(s: T, cipher: &String, password: &String) -> Result { - 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>; } -impl ReadExt for ShadowedStream { +impl ReadExt for ShadowedStream +where + T: AsyncRead + Unpin, +{ fn poll_read_exact(&mut self, cx: &mut Context, size: usize) -> Poll> { 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 AsyncRead for ShadowedStream { +impl AsyncRead for ShadowedStream +where + T: AsyncRead + Unpin, +{ fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context, @@ -104,11 +118,20 @@ impl AsyncRead for ShadowedStream { 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 AsyncRead for ShadowedStream { } } -impl AsyncWrite for ShadowedStream { +impl AsyncWrite for ShadowedStream +where + T: AsyncWrite + Unpin, +{ fn poll_write( mut self: Pin<&mut Self>, cx: &mut Context, @@ -167,17 +193,28 @@ impl AsyncWrite for ShadowedStream { 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 AsyncWrite for ShadowedStream { } struct InnerHalf { - // server: SocketAddr, - cipher: Box, + cipher: AeadCipher, + psk: Vec, } struct Half { @@ -280,7 +317,7 @@ pub struct ShadowedDatagramRecvHalf(Half>); 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, - // server: SocketAddr, - cipher: Box, + cipher: AeadCipher, + psk: Vec, recv_buf: BytesMut, send_buf: BytesMut, } impl ShadowedDatagram { - pub fn new( - socket: Box, - /* server: SocketAddr,*/ cipher: Box, - ) -> Self { - ShadowedDatagram { + pub fn new(socket: Box, cipher: &String, password: &String) -> Result { + 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, - // server: SocketAddr, - cipher: Box, + cipher: &String, + password: &String, buf_size: usize, - ) -> Self { - ShadowedDatagram { + ) -> Result { + 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 { diff --git a/leaf/src/proxy/shadowsocks/udp.rs b/leaf/src/proxy/shadowsocks/udp.rs index 633ad31..5f9a46a 100644 --- a/leaf/src/proxy/shadowsocks/udp.rs +++ b/leaf/src/proxy/shadowsocks/udp.rs @@ -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>, _stream: Option>, ) -> io::Result> { - 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 })); } diff --git a/leaf/src/proxy/tls/tcp.rs b/leaf/src/proxy/tls/tcp.rs index 57102ff..d3ce980 100644 --- a/leaf/src/proxy/tls/tcp.rs +++ b/leaf/src/proxy/tls/tcp.rs @@ -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 { - Ok(rustls::ServerCertVerified::assertion()) - } -} - -async fn wrap_tls( - stream: S, - domain: &str, - alpns: Vec, - insecure: bool, -) -> io::Result> -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, @@ -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")), } diff --git a/leaf/src/proxy/tun/inbound.rs b/leaf/src/proxy/tun/inbound.rs index 9e95b07..2e27b33 100644 --- a/leaf/src/proxy/tun/inbound.rs +++ b/leaf/src/proxy/tun/inbound.rs @@ -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 }; diff --git a/leaf/src/proxy/tun/netstack/lwip b/leaf/src/proxy/tun/netstack/lwip index d20eaab..b72244c 160000 --- a/leaf/src/proxy/tun/netstack/lwip +++ b/leaf/src/proxy/tun/netstack/lwip @@ -1 +1 @@ -Subproject commit d20eaab2f64dcb6573a6f92608ee88b89aee578a +Subproject commit b72244cc5da8408037ce98cf414860bd54fe1ea0 diff --git a/leaf/src/proxy/vmess/crypto.rs b/leaf/src/proxy/vmess/crypto.rs new file mode 100644 index 0000000..23eaaa7 --- /dev/null +++ b/leaf/src/proxy/vmess/crypto.rs @@ -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 { + 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> { + 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> { + 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, + size: usize, + count: u16, +} + +impl VMessAEADSequence { + pub fn new(nonce: Vec, 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> { + 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 + } +} diff --git a/leaf/src/proxy/vmess/mod.rs b/leaf/src/proxy/vmess/mod.rs index 2362d30..a362b8a 100644 --- a/leaf/src/proxy/vmess/mod.rs +++ b/leaf/src/proxy/vmess/mod.rs @@ -1,5 +1,5 @@ +mod crypto; mod vmess; -pub use vmess::*; pub mod tcp; pub mod udp; diff --git a/leaf/src/proxy/vmess/tcp.rs b/leaf/src/proxy/vmess/tcp.rs index 33aa7c3..f5f1ebd 100644 --- a/leaf/src/proxy/vmess/tcp.rs +++ b/leaf/src/proxy/vmess/tcp.rs @@ -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))) } diff --git a/leaf/src/proxy/vmess/udp.rs b/leaf/src/proxy/vmess/udp.rs index e1b140a..59c06aa 100644 --- a/leaf/src/proxy/vmess/udp.rs +++ b/leaf/src/proxy/vmess/udp.rs @@ -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, diff --git a/leaf/src/proxy/vmess/vmess.rs b/leaf/src/proxy/vmess/vmess.rs index f2386eb..9a206de 100644 --- a/leaf/src/proxy/vmess/vmess.rs +++ b/leaf/src/proxy/vmess/vmess.rs @@ -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, - size: usize, - count: u16, -} - -impl VMessAEADSequence { - pub fn new(nonce: Vec, 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 { - 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 { - 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> { - 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> { - 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 { inner: T, sess: ClientSession, - enc: SealingKey, + enc: AeadEncryptor, enc_size_parser: ShakeSizeParser, - dec: OpeningKey, + dec: AeadDecryptor, dec_size_parser: ShakeSizeParser, + tag_len: usize, read_buf: BytesMut, write_buf: BytesMut, read_state: ReadState, @@ -334,10 +205,11 @@ impl VMessAuthStream { pub fn new( s: T, sess: ClientSession, - enc: SealingKey, + enc: AeadEncryptor, enc_size_parser: ShakeSizeParser, - dec: OpeningKey, + dec: AeadDecryptor, dec_size_parser: ShakeSizeParser, + tag_len: usize, ) -> Self { VMessAuthStream { inner: s, @@ -346,6 +218,7 @@ impl VMessAuthStream { 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 AsyncRead for VMessAuthStream { 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 AsyncWrite for VMessAuthStream { 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 AsyncWrite for VMessAuthStream { 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 { diff --git a/misc/build_cross.sh b/misc/build_cross.sh new file mode 100755 index 0000000..f39b66f --- /dev/null +++ b/misc/build_cross.sh @@ -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