From af24da946dd671782cf9ce3528748df9ea147a55 Mon Sep 17 00:00:00 2001 From: eric Date: Tue, 5 Sep 2023 17:35:15 +0800 Subject: [PATCH] outbound/shadowsocks: support customizable salt prefix Note the prefix must specify in percent-encoded form and the length must less than the used cipher key length. --- leaf/Cargo.toml | 3 +- leaf/src/app/outbound/manager.rs | 13 ++++---- leaf/src/app/outbound/selector_cache.rs | 2 +- leaf/src/config/conf/config.rs | 6 ++++ leaf/src/config/geosite.rs | 2 +- leaf/src/config/internal/config.proto | 1 + leaf/src/config/internal/config.rs | 15 ++++++++- leaf/src/config/json/config.rs | 2 ++ leaf/src/proxy/shadowsocks/inbound/stream.rs | 2 +- leaf/src/proxy/shadowsocks/outbound/stream.rs | 32 ++++++++++++++++++- leaf/src/proxy/shadowsocks/shadow.rs | 26 ++++++++++++--- 11 files changed, 87 insertions(+), 17 deletions(-) diff --git a/leaf/Cargo.toml b/leaf/Cargo.toml index 3aae41c..25d48ac 100644 --- a/leaf/Cargo.toml +++ b/leaf/Cargo.toml @@ -88,7 +88,7 @@ config-json = ["serde", "serde_derive", "serde_json"] outbound-direct = [] outbound-drop = [] outbound-redirect = [] -outbound-shadowsocks = ["hkdf", "sha-1", "md-5", "tokio-util"] +outbound-shadowsocks = ["hkdf", "sha-1", "md-5", "percent-encoding", "tokio-util"] outbound-obfs = ["base64", "memchr"] outbound-socks = ["async-socks5"] outbound-trojan = ["sha2", "hex"] @@ -195,6 +195,7 @@ async-socks5 = { version = "0.5", optional = true } hkdf = { version = "0.11", optional = true } md-5 = { version = "0.10", optional = true } sha-1 = { version = "0.9", optional = true } +percent-encoding = { version = "2", optional = true } # Obfs base64 = { version = "0.21", optional = true } diff --git a/leaf/src/app/outbound/manager.rs b/leaf/src/app/outbound/manager.rs index f6703c2..e85d2db 100644 --- a/leaf/src/app/outbound/manager.rs +++ b/leaf/src/app/outbound/manager.rs @@ -165,12 +165,13 @@ impl OutboundManager { let settings = config::ShadowsocksOutboundSettings::parse_from_bytes(&outbound.settings) .map_err(|e| anyhow!("invalid [{}] outbound settings: {}", &tag, e))?; - let stream = Box::new(shadowsocks::outbound::StreamHandler { - address: settings.address.clone(), - port: settings.port as u16, - cipher: settings.method.clone(), - password: settings.password.clone(), - }); + let stream = Box::new(shadowsocks::outbound::StreamHandler::new( + settings.address.clone(), + settings.port as u16, + settings.method.clone(), + settings.password.clone(), + settings.prefix.as_ref().cloned(), + )?); let datagram = Box::new(shadowsocks::outbound::DatagramHandler { address: settings.address, port: settings.port as u16, diff --git a/leaf/src/app/outbound/selector_cache.rs b/leaf/src/app/outbound/selector_cache.rs index 683e9e1..7a6adf5 100644 --- a/leaf/src/app/outbound/selector_cache.rs +++ b/leaf/src/app/outbound/selector_cache.rs @@ -1,5 +1,5 @@ // This file is generated by rust-protobuf 3.2.0. Do not edit -// .proto file is parsed by protoc 3.21.12 +// .proto file is parsed by protoc 24.2 // @generated // https://github.com/rust-lang/rust-clippy/issues/702 diff --git a/leaf/src/config/conf/config.rs b/leaf/src/config/conf/config.rs index c315211..9f41176 100644 --- a/leaf/src/config/conf/config.rs +++ b/leaf/src/config/conf/config.rs @@ -51,6 +51,7 @@ pub struct Proxy { // shadowsocks pub encrypt_method: Option, + pub prefix: Option, // shadowsocks, trojan pub password: Option, @@ -89,6 +90,7 @@ impl Default for Proxy { address: None, port: None, encrypt_method: Some("chacha20-ietf-poly1305".to_string()), + prefix: None, password: None, obfs_type: None, obfs_host: None, @@ -376,6 +378,9 @@ pub fn from_lines(lines: Vec>) -> Result { "encrypt-method" => { proxy.encrypt_method = Some(v.to_string()); } + "prefix" => { + proxy.prefix = Some(v.to_string()); + } "password" => { proxy.password = Some(v.to_string()); } @@ -872,6 +877,7 @@ pub fn to_internal(conf: &mut Config) -> Result { } else { settings.method = "chacha20-ietf-poly1305".to_string(); } + settings.prefix = ext_proxy.prefix.clone(); if let Some(ext_password) = &ext_proxy.password { settings.password = ext_password.clone(); } diff --git a/leaf/src/config/geosite.rs b/leaf/src/config/geosite.rs index f424cd5..3355986 100644 --- a/leaf/src/config/geosite.rs +++ b/leaf/src/config/geosite.rs @@ -1,5 +1,5 @@ // This file is generated by rust-protobuf 3.2.0. Do not edit -// .proto file is parsed by protoc 3.21.12 +// .proto file is parsed by protoc 24.2 // @generated // https://github.com/rust-lang/rust-clippy/issues/702 diff --git a/leaf/src/config/internal/config.proto b/leaf/src/config/internal/config.proto index 2ecde03..65a833b 100644 --- a/leaf/src/config/internal/config.proto +++ b/leaf/src/config/internal/config.proto @@ -105,6 +105,7 @@ message ShadowsocksOutboundSettings { uint32 port = 2; string method = 3; // TODO use enum string password = 4; + optional string prefix = 5; } message ObfsOutboundSettings { diff --git a/leaf/src/config/internal/config.rs b/leaf/src/config/internal/config.rs index ca1614b..0220dc3 100644 --- a/leaf/src/config/internal/config.rs +++ b/leaf/src/config/internal/config.rs @@ -1,5 +1,5 @@ // This file is generated by rust-protobuf 3.2.0. Do not edit -// .proto file is parsed by protoc 3.21.12 +// .proto file is parsed by protoc 24.2 // @generated // https://github.com/rust-lang/rust-clippy/issues/702 @@ -1824,6 +1824,8 @@ pub struct ShadowsocksOutboundSettings { pub method: ::std::string::String, // @@protoc_insertion_point(field:ShadowsocksOutboundSettings.password) pub password: ::std::string::String, + // @@protoc_insertion_point(field:ShadowsocksOutboundSettings.prefix) + pub prefix: ::std::option::Option<::std::string::String>, // special fields // @@protoc_insertion_point(special_field:ShadowsocksOutboundSettings.special_fields) pub special_fields: ::protobuf::SpecialFields, @@ -1863,6 +1865,9 @@ impl ::protobuf::Message for ShadowsocksOutboundSettings { 34 => { self.password = is.read_string()?; }, + 42 => { + self.prefix = ::std::option::Option::Some(is.read_string()?); + }, tag => { ::protobuf::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, @@ -1887,6 +1892,9 @@ impl ::protobuf::Message for ShadowsocksOutboundSettings { if !self.password.is_empty() { my_size += ::protobuf::rt::string_size(4, &self.password); } + if let Some(v) = self.prefix.as_ref() { + my_size += ::protobuf::rt::string_size(5, &v); + } my_size += ::protobuf::rt::unknown_fields_size(self.special_fields.unknown_fields()); self.special_fields.cached_size().set(my_size as u32); my_size @@ -1905,6 +1913,9 @@ impl ::protobuf::Message for ShadowsocksOutboundSettings { if !self.password.is_empty() { os.write_string(4, &self.password)?; } + if let Some(v) = self.prefix.as_ref() { + os.write_string(5, v)?; + } os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } @@ -1926,6 +1937,7 @@ impl ::protobuf::Message for ShadowsocksOutboundSettings { self.port = 0; self.method.clear(); self.password.clear(); + self.prefix = ::std::option::Option::None; self.special_fields.clear(); } @@ -1935,6 +1947,7 @@ impl ::protobuf::Message for ShadowsocksOutboundSettings { port: 0, method: ::std::string::String::new(), password: ::std::string::String::new(), + prefix: ::std::option::Option::None, special_fields: ::protobuf::SpecialFields::new(), }; &instance diff --git a/leaf/src/config/json/config.rs b/leaf/src/config/json/config.rs index 52f107e..85469e7 100644 --- a/leaf/src/config/json/config.rs +++ b/leaf/src/config/json/config.rs @@ -113,6 +113,7 @@ pub struct ShadowsocksOutboundSettings { pub port: Option, pub method: Option, pub password: Option, + pub prefix: Option, } #[derive(Serialize, Deserialize, Debug)] @@ -602,6 +603,7 @@ pub fn to_internal(json: &mut Config) -> Result { if let Some(ext_password) = ext_settings.password { settings.password = ext_password; } + settings.prefix = ext_settings.prefix.as_ref().cloned(); let settings = settings.write_to_bytes().unwrap(); outbound.settings = settings; outbounds.push(outbound); diff --git a/leaf/src/proxy/shadowsocks/inbound/stream.rs b/leaf/src/proxy/shadowsocks/inbound/stream.rs index cf6f760..fdd1590 100644 --- a/leaf/src/proxy/shadowsocks/inbound/stream.rs +++ b/leaf/src/proxy/shadowsocks/inbound/stream.rs @@ -19,7 +19,7 @@ impl InboundStreamHandler for Handler { mut sess: Session, stream: AnyStream, ) -> std::io::Result { - let mut stream = ShadowedStream::new(stream, &self.cipher, &self.password)?; + let mut stream = ShadowedStream::new(stream, &self.cipher, &self.password, None)?; let destination = SocksAddr::read_from(&mut stream, SocksAddrWireType::PortLast).await?; sess.destination = destination; Ok(InboundTransport::Stream(Box::new(stream), sess)) diff --git a/leaf/src/proxy/shadowsocks/outbound/stream.rs b/leaf/src/proxy/shadowsocks/outbound/stream.rs index c7f84e1..271ac81 100644 --- a/leaf/src/proxy/shadowsocks/outbound/stream.rs +++ b/leaf/src/proxy/shadowsocks/outbound/stream.rs @@ -1,5 +1,6 @@ use std::io; +use anyhow::Result; use async_trait::async_trait; use bytes::BytesMut; use tokio::io::AsyncWriteExt; @@ -12,6 +13,30 @@ pub struct Handler { pub port: u16, pub cipher: String, pub password: String, + pub prefix: Option>, +} + +impl Handler { + pub fn new( + address: String, + port: u16, + cipher: String, + password: String, + prefix: Option, + ) -> Result { + let prefix = prefix + .as_ref() + .map(|x| percent_encoding::percent_decode(x.as_bytes()).decode_utf8()) + .transpose()? + .map(|x| x.to_string().into_bytes().into_boxed_slice()); + Ok(Self { + address, + port, + cipher, + password, + prefix, + }) + } } #[async_trait] @@ -26,7 +51,12 @@ impl OutboundStreamHandler for Handler { stream: Option, ) -> io::Result { let stream = stream.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "invalid input"))?; - let mut stream = ShadowedStream::new(stream, &self.cipher, &self.password)?; + let mut stream = ShadowedStream::new( + stream, + &self.cipher, + &self.password, + self.prefix.as_ref().cloned(), + )?; let mut buf = BytesMut::new(); sess.destination .write_buf(&mut buf, SocksAddrWireType::PortLast); diff --git a/leaf/src/proxy/shadowsocks/shadow.rs b/leaf/src/proxy/shadowsocks/shadow.rs index 36c783e..dbec335 100644 --- a/leaf/src/proxy/shadowsocks/shadow.rs +++ b/leaf/src/proxy/shadowsocks/shadow.rs @@ -8,7 +8,7 @@ use futures::{ task::{Context, Poll}, }; use log::*; -use rand::{rngs::StdRng, Rng, SeedableRng}; +use rand::{rngs::StdRng, Rng, RngCore, SeedableRng}; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; use crate::common::crypto::{ @@ -43,10 +43,11 @@ pub struct ShadowedStream { read_state: ReadState, write_state: WriteState, read_pos: usize, + prefix: Option>, } impl ShadowedStream { - pub fn new(s: T, cipher: &str, password: &str) -> io::Result { + pub fn new(s: T, cipher: &str, password: &str, prefix: Option>) -> io::Result { let cipher = AeadCipher::new(cipher).map_err(|e| { io::Error::new( io::ErrorKind::Other, @@ -56,6 +57,18 @@ impl ShadowedStream { let psk = kdf(password, cipher.key_len()).map_err(|e| { io::Error::new(io::ErrorKind::Other, format!("derive key failed: {}", e)) })?; + if let Some(prefix) = prefix.as_ref() { + if prefix.len() > cipher.key_len() { + return Err(io::Error::new( + io::ErrorKind::Other, + format!( + "prefix length exceeding cipher key length: {} > {}", + prefix.len(), + cipher.key_len() + ), + )); + } + } Ok(ShadowedStream { inner: s, cipher, @@ -69,6 +82,7 @@ impl ShadowedStream { read_state: ReadState::WaitingSalt, write_state: WriteState::WaitingSalt, read_pos: 0, + prefix, }) } } @@ -215,10 +229,12 @@ where 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(); + if let Some(prefix) = self.prefix.as_ref().cloned() { + self.write_buf[..prefix.len()].copy_from_slice(&prefix); + rng.fill_bytes(&mut self.write_buf[prefix.len()..salt_size]); + } else { + rng.fill_bytes(&mut self.write_buf[..salt_size]); } - let key = hkdf_sha1( &self.psk, &self.write_buf[..salt_size],