Support ECH

This commit is contained in:
eric committed 2026-03-13 16:58:55 +08:00
1 parent 4dd6f89493
commit 822889c78a
13 files changed
+850 -12

No files matched your search

+2 -2
View File
@@ -16,7 +16,7 @@ argh = "0.1"
path = "../leaf"
default-features = false
features = [
"default-ring",
"default-aws-lc",
"ctrlc",
"auto-reload"
]
@@ -25,7 +25,7 @@ features = [
path = "../leaf"
default-features = false
features = [
"default-ring",
"default-aws-lc",
"ctrlc",
"auto-reload",
"inbound-nf",
+1 -1
View File
@@ -11,7 +11,7 @@ crate-type = ["staticlib", "dylib"]
[features]
default = [
"default-ring",
"default-aws-lc",
"auto-reload",
]
+1 -1
View File
@@ -11,7 +11,7 @@ path = "src/lib.rs"
[features]
default = [
"default-ring"
"default-aws-lc"
]
default-ring = [
+19 -4
View File
@@ -229,10 +229,25 @@ impl InboundManager {
"tls" => {
let settings = config::TlsInboundSettings::parse_from_bytes(&inbound.settings)
.map_err(|e| anyhow!("invalid [{}] inbound settings: {}", &tag, e))?;
let stream = Arc::new(tls::inbound::StreamHandler::new(
settings.certificate.clone(),
settings.certificate_key.clone(),
)?);
let ech_config = if settings.ech_config.is_empty() {
None
} else {
Some(settings.ech_config.clone())
};
let ech_key = if settings.ech_key.is_empty() {
None
} else {
Some(settings.ech_key.clone())
};
let stream = Arc::new(
tls::inbound::StreamHandler::new(
settings.certificate.clone(),
settings.certificate_key.clone(),
ech_config,
ech_key,
)
.map_err(|e| anyhow!("invalid [{}] inbound tls capability: {}", &tag, e))?,
);
let handler = Arc::new(proxy::inbound::Handler::new(
tag.clone(),
Some(stream),
+6
View File
@@ -316,12 +316,18 @@ impl OutboundManager {
} else {
Some(settings.certificate_key.clone())
};
let ech_config_list = if settings.ech_config_list.is_empty() {
None
} else {
Some(settings.ech_config_list.clone())
};
let stream = Arc::new(tls::outbound::StreamHandler::new(
settings.server_name.clone(),
settings.alpn.clone(),
certificate,
certificate_key,
settings.insecure,
ech_config_list,
)?);
HandlerBuilder::default()
.tag(tag.clone())
+49
View File
@@ -100,6 +100,10 @@ pub struct TlsInboundSettings {
pub raw_certificate: Option<Vec<String>>,
#[serde(rename = "rawCertificateKey", alias = "raw_certificate_key")]
pub raw_certificate_key: Option<Vec<String>>,
#[serde(rename = "echConfig", alias = "ech_config")]
pub ech_config: Option<String>,
#[serde(rename = "echKey", alias = "ech_key")]
pub ech_key: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
@@ -220,6 +224,8 @@ pub struct TlsOutboundSettings {
#[serde(rename = "rawCertificateKey", alias = "raw_certificate_key")]
pub raw_certificate_key: Option<Vec<String>>,
pub insecure: Option<bool>,
#[serde(rename = "echConfigList", alias = "ech_config_list")]
pub ech_config_list: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
@@ -518,6 +524,17 @@ fn is_inline_certificate(certificate: &str) -> bool {
certificate.contains("-----BEGIN")
}
fn validate_non_empty_str(value: &str, field_name: &str, protocol: &str) -> Result<()> {
if value.trim().is_empty() {
return Err(anyhow::anyhow!(
"invalid [{}] settings: {} cannot be empty",
protocol,
field_name
));
}
Ok(())
}
pub fn to_internal(mut config: Config) -> Result<internal::Config> {
let mut log = internal::Log::new();
if let Some(ext_log) = &config.log {
@@ -862,6 +879,22 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
} => {
inbound.protocol = "tls".to_string();
if let Some(ext_settings) = ext_settings {
if ext_settings.ech_config.is_some() || ext_settings.ech_key.is_some() {
match (&ext_settings.ech_config, &ext_settings.ech_key) {
(Some(ech_config), Some(ech_key)) => {
validate_non_empty_str(ech_config, "echConfig", "tls inbound")?;
validate_non_empty_str(ech_key, "echKey", "tls inbound")?;
return Err(anyhow::anyhow!(
"invalid [tls inbound] settings: inbound ECH is not supported yet; remove echConfig and echKey"
));
}
_ => {
return Err(anyhow::anyhow!(
"invalid [tls inbound] settings: echConfig and echKey must be set together"
))
}
}
}
let mut settings = internal::TlsInboundSettings::new();
if let Some(ext_raw_certificate) = &ext_settings.raw_certificate {
settings.certificate = ext_raw_certificate.join("\n");
@@ -891,6 +924,12 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
settings.certificate_key = path;
}
}
if let Some(ext_ech_config) = &ext_settings.ech_config {
settings.ech_config = ext_ech_config.clone();
}
if let Some(ext_ech_key) = &ext_settings.ech_key {
settings.ech_key = ext_ech_key.clone();
}
let settings = settings.write_to_bytes().unwrap();
inbound.settings = settings;
}
@@ -1119,6 +1158,13 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
} => {
outbound.protocol = "tls".to_string();
if let Some(ext_settings) = ext_settings {
if let Some(ext_ech_config_list) = &ext_settings.ech_config_list {
validate_non_empty_str(
ext_ech_config_list,
"echConfigList",
"tls outbound",
)?;
}
let mut settings = internal::TlsOutboundSettings::new();
if let Some(ext_server_name) = &ext_settings.server_name {
settings.server_name = ext_server_name.clone();
@@ -1157,6 +1203,9 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
if let Some(ext_insecure) = ext_settings.insecure {
settings.insecure = ext_insecure;
}
if let Some(ext_ech_config_list) = &ext_settings.ech_config_list {
settings.ech_config_list = ext_ech_config_list.clone();
}
let settings = settings.write_to_bytes().unwrap();
outbound.settings = settings;
}
+204
View File
@@ -75,6 +75,7 @@ pub struct Proxy {
pub tls: Option<bool>,
pub tls_cert: Option<String>,
pub tls_insecure: Option<bool>,
pub tls_ech: Option<String>,
pub ws_path: Option<String>,
pub ws_host: Option<String>,
@@ -117,6 +118,7 @@ impl Default for Proxy {
tls: Some(false),
tls_cert: None,
tls_insecure: Some(false),
tls_ech: None,
ws_path: None,
ws_host: None,
sni: None,
@@ -214,6 +216,7 @@ pub struct Config {
pub rule: Option<Vec<Rule>>,
pub host: Option<HashMap<String, Vec<String>>>,
pub certificates: Option<HashMap<String, String>>,
pub ech_configs: Option<HashMap<String, String>>,
}
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
@@ -315,6 +318,81 @@ where
certificates
}
fn get_ech_sections<'a, I>(lines: I) -> HashMap<String, String>
where
I: Iterator<Item = &'a io::Result<String>>,
{
let mut ech_configs = HashMap::new();
let mut current_name: Option<String> = None;
let mut current_lines: Vec<String> = Vec::new();
for line in lines {
let line = match line {
Ok(line) => line,
Err(_) => continue,
};
let trimmed = line.trim();
if let Some(section) = get_section(trimmed) {
if let Some(name) = current_name.take() {
if !current_lines.is_empty() {
let mut content = current_lines.join("\n");
content.push('\n');
ech_configs.insert(name, content);
}
current_lines.clear();
}
let lower = section.to_lowercase();
if let Some(name) = section.strip_prefix("Ech.") {
let name = name.trim();
if !name.is_empty() {
current_name = Some(name.to_string());
}
} else if lower.starts_with("ech.") {
let name = &section["ech.".len()..];
let name = name.trim();
if !name.is_empty() {
current_name = Some(name.to_string());
}
} else if lower.starts_with("ech_") {
let name = &section["ech_".len()..];
let name = name.trim();
if !name.is_empty() {
current_name = Some(name.to_string());
}
} else if lower.starts_with("ech ") {
let name = &section["ech ".len()..];
let name = name.trim();
if !name.is_empty() {
current_name = Some(name.to_string());
}
} else if lower.starts_with("ech") {
let name = &section["ech".len()..];
let name = name.trim();
if !name.is_empty() {
current_name = Some(name.to_string());
}
}
continue;
}
if current_name.is_some() {
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
current_lines.push(trimmed.to_string());
}
}
if let Some(name) = current_name.take() {
if !current_lines.is_empty() {
let mut content = current_lines.join("\n");
content.push('\n');
ech_configs.insert(name, content);
}
}
ech_configs
}
fn get_lines_by_section<'a, I>(section: &str, lines: I) -> Vec<String>
where
I: Iterator<Item = &'a io::Result<String>>,
@@ -373,6 +451,7 @@ where
pub fn from_lines(lines: Vec<io::Result<String>>) -> Result<Config> {
let certificates = get_certificate_sections(lines.iter());
let ech_configs = get_ech_sections(lines.iter());
let env_lines = get_lines_by_section("Env", lines.iter());
for line in env_lines {
let parts: Vec<&str> = line
@@ -554,6 +633,9 @@ pub fn from_lines(lines: Vec<io::Result<String>>) -> Result<Config> {
"tls-insecure" => {
proxy.tls_insecure = if v == "true" { Some(true) } else { Some(false) }
}
"tls-ech" | "ech-config-list" => {
proxy.tls_ech = Some(v.to_string());
}
"ws-path" => {
proxy.ws_path = Some(v.to_string());
}
@@ -889,6 +971,11 @@ pub fn from_lines(lines: Vec<io::Result<String>>) -> Result<Config> {
} else {
Some(certificates)
},
ech_configs: if ech_configs.is_empty() {
None
} else {
Some(ech_configs)
},
})
}
@@ -1009,6 +1096,7 @@ pub fn to_common(conf: &Config) -> Result<common::Config> {
let mut outbounds = Vec::new();
let certificates = conf.certificates.as_ref();
let ech_configs = conf.ech_configs.as_ref();
let resolve_cert = |value: &Option<String>| -> Option<String> {
let value = value.as_ref()?;
if let Some(certificates) = certificates {
@@ -1018,6 +1106,15 @@ pub fn to_common(conf: &Config) -> Result<common::Config> {
}
Some(value.clone())
};
let resolve_ech = |value: &Option<String>| -> Option<String> {
let value = value.as_ref()?;
if let Some(ech_configs) = ech_configs {
if let Some(content) = ech_configs.get(value) {
return Some(content.clone());
}
}
Some(value.clone())
};
if let Some(ext_proxies) = &conf.proxy {
for ext_proxy in ext_proxies {
let protocol = match ext_proxy.protocol.as_str() {
@@ -1180,6 +1277,7 @@ pub fn to_common(conf: &Config) -> Result<common::Config> {
raw_certificate: None,
raw_certificate_key: None,
insecure: ext_proxy.tls_insecure,
ech_config_list: resolve_ech(&ext_proxy.tls_ech),
}),
},
});
@@ -1478,6 +1576,7 @@ pub fn from_string(s: &str) -> Result<internal::Config> {
#[cfg(test)]
mod tests {
use super::*;
use protobuf::Message;
#[test]
fn test_trojan_tls_outbound_order() {
@@ -1537,6 +1636,111 @@ Vmess = vmess, 1.2.3.4, 443, username, amux=true, sni=www.google.com
}
}
#[test]
fn test_trojan_tls_ech_mapping() {
let conf = r#"
[Proxy]
Trojan = trojan, 1.2.3.4, 443, password, sni=www.google.com, tls-ech=AQID
"#;
let lines: Vec<io::Result<String>> = conf.lines().map(|s| Ok(s.to_string())).collect();
let config = from_lines(lines).unwrap();
let common = to_common(&config).unwrap();
let outbounds = common.outbounds.unwrap();
let tls_outbound = outbounds
.iter()
.find(|o| o.tag == Some("Trojan_tls_xxx".to_string()))
.unwrap();
if let common::OutboundSettings::Tls { settings } = &tls_outbound.settings {
assert_eq!(
settings.as_ref().unwrap().ech_config_list,
Some("AQID".to_string())
);
} else {
panic!("Not tls outbound: {:?}", tls_outbound.settings);
}
let internal = to_internal(&config).unwrap();
let tls_outbound = internal
.outbounds
.iter()
.find(|o| o.tag == "Trojan_tls_xxx")
.unwrap();
let tls_settings =
crate::config::internal::TlsOutboundSettings::parse_from_bytes(&tls_outbound.settings)
.unwrap();
assert_eq!(tls_settings.ech_config_list, "AQID".to_string());
}
#[test]
fn test_trojan_tls_ech_mapping_from_section() {
let conf = r#"
[Proxy]
Trojan = trojan, 1.2.3.4, 443, password, sni=www.google.com, tls-ech=myech
[Ech.myech]
AQI=
"#;
let lines: Vec<io::Result<String>> = conf.lines().map(|s| Ok(s.to_string())).collect();
let config = from_lines(lines).unwrap();
let common = to_common(&config).unwrap();
let outbounds = common.outbounds.unwrap();
let tls_outbound = outbounds
.iter()
.find(|o| o.tag == Some("Trojan_tls_xxx".to_string()))
.unwrap();
if let common::OutboundSettings::Tls { settings } = &tls_outbound.settings {
assert_eq!(
settings
.as_ref()
.unwrap()
.ech_config_list
.as_deref()
.map(str::trim),
Some("AQI=")
);
} else {
panic!("Not tls outbound: {:?}", tls_outbound.settings);
}
let internal = to_internal(&config).unwrap();
let tls_outbound = internal
.outbounds
.iter()
.find(|o| o.tag == "Trojan_tls_xxx")
.unwrap();
let tls_settings =
crate::config::internal::TlsOutboundSettings::parse_from_bytes(&tls_outbound.settings)
.unwrap();
assert_eq!(tls_settings.ech_config_list.trim(), "AQI=");
}
#[test]
fn test_trojan_tls_ech_validation() {
let mut proxy = Proxy::default();
proxy.tag = "Trojan".to_string();
proxy.protocol = "trojan".to_string();
proxy.address = Some("1.2.3.4".to_string());
proxy.port = Some(443);
proxy.password = Some("password".to_string());
proxy.sni = Some("www.google.com".to_string());
proxy.tls_ech = Some(" ".to_string());
let config = Config {
general: None,
proxy: Some(vec![proxy]),
proxy_group: None,
rule: None,
host: None,
certificates: None,
ech_configs: None,
};
let err = to_internal(&config).unwrap_err();
assert!(err.to_string().contains("echConfigList cannot be empty"));
}
#[test]
fn test_wintun_conf() {
let conf = r#"
+3
View File
@@ -96,6 +96,8 @@ message QuicInboundSettings {
message TlsInboundSettings {
string certificate = 1;
string certificate_key = 2;
string ech_config = 3;
string ech_key = 4;
}
message ChainInboundSettings {
@@ -157,6 +159,7 @@ message TlsOutboundSettings {
string certificate = 3;
bool insecure = 4;
string certificate_key = 5;
string ech_config_list = 6;
}
message WebSocketOutboundSettings {
+39
View File
@@ -1605,6 +1605,10 @@ pub struct TlsInboundSettings {
pub certificate: ::std::string::String,
// @@protoc_insertion_point(field:TlsInboundSettings.certificate_key)
pub certificate_key: ::std::string::String,
// @@protoc_insertion_point(field:TlsInboundSettings.ech_config)
pub ech_config: ::std::string::String,
// @@protoc_insertion_point(field:TlsInboundSettings.ech_key)
pub ech_key: ::std::string::String,
// special fields
// @@protoc_insertion_point(special_field:TlsInboundSettings.special_fields)
pub special_fields: ::protobuf::SpecialFields,
@@ -1638,6 +1642,12 @@ impl ::protobuf::Message for TlsInboundSettings {
18 => {
self.certificate_key = is.read_string()?;
},
26 => {
self.ech_config = is.read_string()?;
},
34 => {
self.ech_key = is.read_string()?;
},
tag => {
::protobuf::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?;
},
@@ -1656,6 +1666,12 @@ impl ::protobuf::Message for TlsInboundSettings {
if !self.certificate_key.is_empty() {
my_size += ::protobuf::rt::string_size(2, &self.certificate_key);
}
if !self.ech_config.is_empty() {
my_size += ::protobuf::rt::string_size(3, &self.ech_config);
}
if !self.ech_key.is_empty() {
my_size += ::protobuf::rt::string_size(4, &self.ech_key);
}
my_size += ::protobuf::rt::unknown_fields_size(self.special_fields.unknown_fields());
self.special_fields.cached_size().set(my_size as u32);
my_size
@@ -1668,6 +1684,12 @@ impl ::protobuf::Message for TlsInboundSettings {
if !self.certificate_key.is_empty() {
os.write_string(2, &self.certificate_key)?;
}
if !self.ech_config.is_empty() {
os.write_string(3, &self.ech_config)?;
}
if !self.ech_key.is_empty() {
os.write_string(4, &self.ech_key)?;
}
os.write_unknown_fields(self.special_fields.unknown_fields())?;
::std::result::Result::Ok(())
}
@@ -1687,6 +1709,8 @@ impl ::protobuf::Message for TlsInboundSettings {
fn clear(&mut self) {
self.certificate.clear();
self.certificate_key.clear();
self.ech_config.clear();
self.ech_key.clear();
self.special_fields.clear();
}
@@ -1694,6 +1718,8 @@ impl ::protobuf::Message for TlsInboundSettings {
static instance: TlsInboundSettings = TlsInboundSettings {
certificate: ::std::string::String::new(),
certificate_key: ::std::string::String::new(),
ech_config: ::std::string::String::new(),
ech_key: ::std::string::String::new(),
special_fields: ::protobuf::SpecialFields::new(),
};
&instance
@@ -2744,6 +2770,8 @@ pub struct TlsOutboundSettings {
pub insecure: bool,
// @@protoc_insertion_point(field:TlsOutboundSettings.certificate_key)
pub certificate_key: ::std::string::String,
// @@protoc_insertion_point(field:TlsOutboundSettings.ech_config_list)
pub ech_config_list: ::std::string::String,
// special fields
// @@protoc_insertion_point(special_field:TlsOutboundSettings.special_fields)
pub special_fields: ::protobuf::SpecialFields,
@@ -2786,6 +2814,9 @@ impl ::protobuf::Message for TlsOutboundSettings {
42 => {
self.certificate_key = is.read_string()?;
},
50 => {
self.ech_config_list = is.read_string()?;
},
tag => {
::protobuf::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?;
},
@@ -2813,6 +2844,9 @@ impl ::protobuf::Message for TlsOutboundSettings {
if !self.certificate_key.is_empty() {
my_size += ::protobuf::rt::string_size(5, &self.certificate_key);
}
if !self.ech_config_list.is_empty() {
my_size += ::protobuf::rt::string_size(6, &self.ech_config_list);
}
my_size += ::protobuf::rt::unknown_fields_size(self.special_fields.unknown_fields());
self.special_fields.cached_size().set(my_size as u32);
my_size
@@ -2834,6 +2868,9 @@ impl ::protobuf::Message for TlsOutboundSettings {
if !self.certificate_key.is_empty() {
os.write_string(5, &self.certificate_key)?;
}
if !self.ech_config_list.is_empty() {
os.write_string(6, &self.ech_config_list)?;
}
os.write_unknown_fields(self.special_fields.unknown_fields())?;
::std::result::Result::Ok(())
}
@@ -2856,6 +2893,7 @@ impl ::protobuf::Message for TlsOutboundSettings {
self.certificate.clear();
self.insecure = false;
self.certificate_key.clear();
self.ech_config_list.clear();
self.special_fields.clear();
}
@@ -2866,6 +2904,7 @@ impl ::protobuf::Message for TlsOutboundSettings {
certificate: ::std::string::String::new(),
insecure: false,
certificate_key: ::std::string::String::new(),
ech_config_list: ::std::string::String::new(),
special_fields: ::protobuf::SpecialFields::new(),
};
&instance
+117
View File
@@ -1,3 +1,5 @@
use protobuf::Message;
#[test]
fn test_config() {
let json_str = r#"
@@ -140,3 +142,118 @@ fn test_dns_config() {
assert_eq!(dns.servers.as_ref().unwrap().len(), 1);
assert_eq!(dns.servers.as_ref().unwrap()[0], "1.1.1.1");
}
#[test]
fn test_tls_outbound_ech_config_mapping() {
let json_str = r#"
{
"outbounds": [
{
"protocol": "tls",
"tag": "tls_out",
"settings": {
"serverName": "example.com",
"echConfigList": "test-ech-config-list"
}
}
]
}
"#;
let config = crate::config::json::from_string(json_str).unwrap();
let outbound =
crate::config::TlsOutboundSettings::parse_from_bytes(&config.outbounds[0].settings)
.unwrap();
assert_eq!(outbound.ech_config_list, "test-ech-config-list");
}
#[test]
fn test_tls_outbound_ech_config_mapping_aliases() {
let json_str = r#"
{
"outbounds": [
{
"protocol": "tls",
"tag": "tls_out",
"settings": {
"server_name": "example.com",
"ech_config_list": "alias-ech-config-list"
}
}
]
}
"#;
let config = crate::config::json::from_string(json_str).unwrap();
let outbound =
crate::config::TlsOutboundSettings::parse_from_bytes(&config.outbounds[0].settings)
.unwrap();
assert_eq!(outbound.ech_config_list, "alias-ech-config-list");
}
#[test]
fn test_tls_inbound_ech_validation() {
let json_str = r#"
{
"inbounds": [
{
"tag": "tls_in",
"protocol": "tls",
"address": "127.0.0.1",
"port": 1443,
"settings": {
"certificate": "cert.pem",
"certificateKey": "key.pem",
"echConfig": "only-config"
}
}
]
}
"#;
assert!(crate::config::json::from_string(json_str).is_err());
}
#[test]
fn test_tls_inbound_ech_unsupported() {
let json_str = r#"
{
"inbounds": [
{
"tag": "tls_in",
"protocol": "tls",
"address": "127.0.0.1",
"port": 1443,
"settings": {
"certificate": "cert.pem",
"certificateKey": "key.pem",
"echConfig": "AQID",
"echKey": "BAUG"
}
}
]
}
"#;
let err = crate::config::json::from_string(json_str).unwrap_err();
assert!(err.to_string().contains("inbound ECH is not supported yet"));
}
#[test]
fn test_tls_outbound_ech_validation() {
let json_str = r#"
{
"outbounds": [
{
"protocol": "tls",
"tag": "tls_out",
"settings": {
"serverName": "example.com",
"echConfigList": " "
}
}
]
}
"#;
assert!(crate::config::json::from_string(json_str).is_err());
}
+1
View File
@@ -81,6 +81,7 @@ async fn single_health_check(
None,
None,
false,
None,
) else {
return Measure::new(idx, u128::MAX, tag);
};
+202 -1
View File
@@ -67,9 +67,23 @@ fn load_keys(certificate_key: &str) -> io::Result<Vec<PrivateKeyDer<'static>>> {
}
impl Handler {
pub fn new(certificate: String, certificate_key: String) -> Result<Self> {
pub fn new(
certificate: String,
certificate_key: String,
ech_config: Option<String>,
ech_key: Option<String>,
) -> Result<Self> {
#[cfg(feature = "rustls-tls")]
{
let ech = load_ech(ech_config.as_deref(), ech_key.as_deref())?;
if ech.is_some() {
tracing::error!(
"tls inbound ech is configured but inbound ech is not supported by current rustls implementation"
);
return Err(anyhow::anyhow!(
"tls inbound ech is not supported yet; remove echConfig and echKey"
));
}
let certs = load_certs(&certificate).map_err(|e| {
anyhow::anyhow!("load certificates from {} failed: {}", certificate, e)
})?;
@@ -96,6 +110,144 @@ impl Handler {
}
}
fn load_ech(
ech_config: Option<&str>,
ech_key: Option<&str>,
) -> io::Result<Option<(Vec<u8>, Vec<u8>)>> {
match (ech_config, ech_key) {
(None, None) => Ok(None),
(Some(config), Some(key)) => {
let config = decode_ech_blob(config)?;
let key = decode_ech_blob(key)?;
if config.is_empty() || key.is_empty() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid ech config or key",
));
}
Ok(Some((config, key)))
}
_ => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"ech config and key must be set together",
)),
}
}
fn decode_ech_blob(input: &str) -> io::Result<Vec<u8>> {
let value = input.trim();
if value.starts_with("-----BEGIN") {
let mut encoded = String::new();
for line in value.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with("-----BEGIN") || line.starts_with("-----END") {
continue;
}
encoded.push_str(line);
}
if encoded.is_empty() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid ech pem",
));
}
return decode_base64(&encoded);
}
decode_base64(value)
}
fn decode_base64(data: &str) -> io::Result<Vec<u8>> {
fn value(byte: u8) -> Option<u8> {
match byte {
b'A'..=b'Z' => Some(byte - b'A'),
b'a'..=b'z' => Some(byte - b'a' + 26),
b'0'..=b'9' => Some(byte - b'0' + 52),
b'+' | b'-' => Some(62),
b'/' | b'_' => Some(63),
_ => None,
}
}
fn decode_chunk(chunk: &[u8; 4], output: &mut Vec<u8>) -> io::Result<()> {
if chunk[0] == 64 || chunk[1] == 64 {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid base64 padding",
));
}
output.push((chunk[0] << 2) | (chunk[1] >> 4));
match (chunk[2], chunk[3]) {
(64, 64) => Ok(()),
(64, _) => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid base64 padding",
)),
(c2, 64) => {
output.push(((chunk[1] & 0x0f) << 4) | (c2 >> 2));
Ok(())
}
(c2, c3) => {
output.push(((chunk[1] & 0x0f) << 4) | (c2 >> 2));
output.push(((c2 & 0x03) << 6) | c3);
Ok(())
}
}
}
let mut output = Vec::with_capacity(data.len() * 3 / 4);
let mut chunk = [0_u8; 4];
let mut chunk_len = 0_usize;
let mut seen_padding = false;
for byte in data.bytes() {
if byte.is_ascii_whitespace() {
continue;
}
if byte == b'=' {
seen_padding = true;
chunk[chunk_len] = 64;
chunk_len += 1;
} else if let Some(decoded) = value(byte) {
if seen_padding {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid base64 padding",
));
}
chunk[chunk_len] = decoded;
chunk_len += 1;
} else {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid base64 character",
));
}
if chunk_len == 4 {
decode_chunk(&chunk, &mut output)?;
chunk = [0_u8; 4];
chunk_len = 0;
}
}
match chunk_len {
0 => Ok(output),
2 => {
output.push((chunk[0] << 2) | (chunk[1] >> 4));
Ok(output)
}
3 => {
output.push((chunk[0] << 2) | (chunk[1] >> 4));
output.push(((chunk[1] & 0x0f) << 4) | (chunk[2] >> 2));
Ok(output)
}
_ => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid base64 length",
)),
}
}
#[async_trait]
impl InboundStreamHandler for Handler {
async fn handle<'a>(
@@ -121,3 +273,52 @@ impl InboundStreamHandler for Handler {
))
}
}
#[cfg(test)]
mod tests {
use super::{decode_base64, decode_ech_blob, load_ech};
#[test]
fn test_decode_base64_standard_and_urlsafe() {
assert_eq!(decode_base64("AQID").unwrap(), vec![1, 2, 3]);
assert_eq!(decode_base64("AQI=").unwrap(), vec![1, 2]);
assert_eq!(decode_base64("AQI").unwrap(), vec![1, 2]);
assert_eq!(decode_base64("-_8=").unwrap(), vec![251, 255]);
}
#[test]
fn test_decode_base64_invalid_input() {
assert!(decode_base64("A").is_err());
assert!(decode_base64("AA=A").is_err());
assert!(decode_base64("AA$A").is_err());
}
#[test]
fn test_decode_ech_blob_pem() {
let value = "-----BEGIN ECH-----\nAQID\n-----END ECH-----";
assert_eq!(decode_ech_blob(value).unwrap(), vec![1, 2, 3]);
}
#[test]
fn test_load_ech_pair() {
assert!(load_ech(None, None).unwrap().is_none());
assert!(load_ech(Some("AQID"), Some("AQID")).unwrap().is_some());
assert!(load_ech(Some("AQID"), None).is_err());
}
#[cfg(feature = "rustls-tls")]
#[test]
fn test_new_with_ech_rejected() {
let rcgen::CertifiedKey { cert, key_pair } =
rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap();
let cert_pem = cert.pem();
let key_pem = key_pair.serialize_pem();
let result = super::Handler::new(
cert_pem,
key_pem,
Some("AQID".to_string()),
Some("BAUG".to_string()),
);
assert!(result.is_err());
}
}
+206 -3
View File
@@ -17,6 +17,11 @@ use {
},
};
#[cfg(all(feature = "rustls-tls", feature = "rustls-tls-aws-lc"))]
use tokio_rustls::rustls::client::{EchConfig, EchMode};
#[cfg(all(feature = "rustls-tls", feature = "rustls-tls-aws-lc"))]
use tokio_rustls::rustls::pki_types::{pem::PemObject, EchConfigListBytes};
#[cfg(feature = "openssl-tls")]
use {
openssl::ssl::{Ssl, SslConnector, SslMethod},
@@ -90,6 +95,7 @@ mod dangerous {
pub struct Handler {
server_name: String,
ech_enabled: bool,
#[cfg(feature = "rustls-tls")]
tls_config: Option<Arc<ClientConfig>>,
#[cfg(feature = "openssl-tls")]
@@ -103,9 +109,11 @@ impl Handler {
certificate: Option<String>,
certificate_key: Option<String>,
insecure: bool,
ech_config_list: Option<String>,
) -> Result<Self> {
let mut handler = Handler {
server_name,
ech_enabled: false,
#[cfg(feature = "rustls-tls")]
tls_config: None,
#[cfg(feature = "openssl-tls")]
@@ -137,9 +145,43 @@ impl Handler {
#[cfg(not(feature = "rustls-tls-aws-lc"))]
let provider = rustls::crypto::ring::default_provider().into();
let builder = ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
let builder = ClientConfig::builder_with_provider(provider);
#[cfg(feature = "rustls-tls-aws-lc")]
let builder = if let Some(ech_config_list) = ech_config_list.as_ref() {
let ech_config_list = decode_ech_config_list(ech_config_list)?;
let ech_config = EchConfig::new(
ech_config_list,
rustls::crypto::aws_lc_rs::hpke::ALL_SUPPORTED_SUITES,
)
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;
builder
.with_ech(EchMode::Enable(ech_config))
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?
} else {
builder
.with_safe_default_protocol_versions()
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?
};
#[cfg(feature = "rustls-tls-aws-lc")]
{
handler.ech_enabled = ech_config_list.is_some();
if handler.ech_enabled {
tracing::trace!("tls outbound ech configured");
} else {
tracing::trace!("tls outbound ech not configured");
}
}
#[cfg(not(feature = "rustls-tls-aws-lc"))]
let builder = {
if ech_config_list.is_some() {
return Err(anyhow::anyhow!(
"tls outbound ech requires rustls-tls-aws-lc"
));
}
builder
.with_safe_default_protocol_versions()
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?
};
let mut config = if insecure {
let builder = builder
@@ -189,6 +231,110 @@ impl Handler {
}
}
#[cfg(all(feature = "rustls-tls", feature = "rustls-tls-aws-lc"))]
fn decode_ech_config_list(ech_config_list: &str) -> io::Result<EchConfigListBytes<'static>> {
let ech_config_list = ech_config_list.trim();
if ech_config_list.starts_with("-----BEGIN") {
return EchConfigListBytes::from_pem_slice(ech_config_list.as_bytes())
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))
.map(EchConfigListBytes::into_owned);
}
decode_base64(ech_config_list).map(EchConfigListBytes::from)
}
#[cfg(all(feature = "rustls-tls", any(feature = "rustls-tls-aws-lc", test)))]
fn decode_base64(data: &str) -> io::Result<Vec<u8>> {
fn value(byte: u8) -> Option<u8> {
match byte {
b'A'..=b'Z' => Some(byte - b'A'),
b'a'..=b'z' => Some(byte - b'a' + 26),
b'0'..=b'9' => Some(byte - b'0' + 52),
b'+' | b'-' => Some(62),
b'/' | b'_' => Some(63),
_ => None,
}
}
fn decode_chunk(chunk: &[u8; 4], output: &mut Vec<u8>) -> io::Result<()> {
if chunk[0] == 64 || chunk[1] == 64 {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid base64 padding",
));
}
output.push((chunk[0] << 2) | (chunk[1] >> 4));
match (chunk[2], chunk[3]) {
(64, 64) => Ok(()),
(64, _) => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid base64 padding",
)),
(c2, 64) => {
output.push(((chunk[1] & 0x0f) << 4) | (c2 >> 2));
Ok(())
}
(c2, c3) => {
output.push(((chunk[1] & 0x0f) << 4) | (c2 >> 2));
output.push(((c2 & 0x03) << 6) | c3);
Ok(())
}
}
}
let mut output = Vec::with_capacity(data.len() * 3 / 4);
let mut chunk = [0_u8; 4];
let mut chunk_len = 0_usize;
let mut seen_padding = false;
for byte in data.bytes() {
if byte.is_ascii_whitespace() {
continue;
}
if byte == b'=' {
seen_padding = true;
chunk[chunk_len] = 64;
chunk_len += 1;
} else if let Some(decoded) = value(byte) {
if seen_padding {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid base64 padding",
));
}
chunk[chunk_len] = decoded;
chunk_len += 1;
} else {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid base64 character",
));
}
if chunk_len == 4 {
decode_chunk(&chunk, &mut output)?;
chunk = [0_u8; 4];
chunk_len = 0;
}
}
match chunk_len {
0 => Ok(output),
2 => {
output.push((chunk[0] << 2) | (chunk[1] >> 4));
Ok(output)
}
3 => {
output.push((chunk[0] << 2) | (chunk[1] >> 4));
output.push(((chunk[1] & 0x0f) << 4) | (chunk[2] >> 2));
Ok(output)
}
_ => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid base64 length",
)),
}
}
#[async_trait]
impl OutboundStreamHandler for Handler {
fn connect_addr(&self) -> OutboundConnect {
@@ -211,7 +357,11 @@ impl OutboundStreamHandler for Handler {
if let Some(stream) = stream {
#[cfg(feature = "rustls-tls")]
if let Some(tls_config) = self.tls_config.as_ref() {
trace!("handling TLS {} with rustls", &name);
trace!(
"handling TLS {} with rustls, ech_enabled={}",
&name,
self.ech_enabled
);
let connector = TlsConnector::from(tls_config.clone());
let domain = ServerName::try_from(name.as_str()).map_err(|e| {
io::Error::new(
@@ -269,3 +419,56 @@ impl OutboundStreamHandler for Handler {
}
}
}
#[cfg(all(test, feature = "rustls-tls"))]
mod tests {
use super::{decode_base64, Handler};
#[test]
fn test_decode_base64_standard_and_urlsafe() {
assert_eq!(decode_base64("AQID").unwrap(), vec![1, 2, 3]);
assert_eq!(decode_base64("AQI=").unwrap(), vec![1, 2]);
assert_eq!(decode_base64("AQI").unwrap(), vec![1, 2]);
assert_eq!(decode_base64("-_8=").unwrap(), vec![251, 255]);
}
#[test]
fn test_decode_base64_invalid_input() {
assert!(decode_base64("A").is_err());
assert!(decode_base64("AA=A").is_err());
assert!(decode_base64("AA$A").is_err());
}
#[cfg(not(feature = "rustls-tls-aws-lc"))]
#[test]
fn test_new_with_ech_requires_aws_lc() {
let result = Handler::new(
"localhost".to_string(),
vec![],
None,
None,
false,
Some("AQID".to_string()),
);
assert!(result.is_err());
assert!(result
.err()
.unwrap()
.to_string()
.contains("rustls-tls-aws-lc"));
}
#[cfg(feature = "rustls-tls-aws-lc")]
#[test]
fn test_new_with_invalid_ech_config_list_fails() {
let result = Handler::new(
"localhost".to_string(),
vec![],
None,
None,
false,
Some("$$$".to_string()),
);
assert!(result.is_err());
}
}