Skip to content

Commit 530ced7

Browse files
author
chechunchi
committed
fix comment from copilot
1 parent 205b3d5 commit 530ced7

13 files changed

Lines changed: 105 additions & 112 deletions

File tree

ci-bench/src/main.rs

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,17 @@ use std::path::{Path, PathBuf};
88
use std::sync::Arc;
99
use std::time::Instant;
1010

11+
use crate::benchmark::{
12+
get_reported_instr_count, validate_benchmarks, Benchmark, BenchmarkKind, BenchmarkParams,
13+
ResumptionKind,
14+
};
15+
use crate::callgrind::{CallgrindRunner, CountInstructions};
16+
use crate::util::async_io::{self, AsyncRead, AsyncWrite};
17+
use crate::util::transport::{
18+
read_handshake_message, read_plaintext_to_end_bounded, send_handshake_message,
19+
write_all_plaintext_bounded,
20+
};
21+
use crate::util::KeyType;
1122
use anyhow::Context;
1223
use async_trait::async_trait;
1324
use clap::{Parser, Subcommand, ValueEnum};
@@ -26,17 +37,6 @@ use watfaq_rustls::{
2637
CipherSuite, ClientConfig, ClientConnection, HandshakeKind, ProtocolVersion, RootCertStore,
2738
ServerConfig, ServerConnection,
2839
};
29-
use crate::benchmark::{
30-
get_reported_instr_count, validate_benchmarks, Benchmark, BenchmarkKind, BenchmarkParams,
31-
ResumptionKind,
32-
};
33-
use crate::callgrind::{CallgrindRunner, CountInstructions};
34-
use crate::util::async_io::{self, AsyncRead, AsyncWrite};
35-
use crate::util::transport::{
36-
read_handshake_message, read_plaintext_to_end_bounded, send_handshake_message,
37-
write_all_plaintext_bounded,
38-
};
39-
use crate::util::KeyType;
4040

4141
mod benchmark;
4242
mod callgrind;

ci-bench/src/util.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -290,8 +290,7 @@ pub mod async_io {
290290

291291
fn poll(mut self: Pin<&mut Self>, _: &mut task::Context<'_>) -> Poll<Self::Output> {
292292
if !self.writer.inner.open.get() {
293-
return Poll::Ready(Err(io::Error::new(
294-
io::ErrorKind::Other,
293+
return Poll::Ready(Err(io::Error::other(
295294
"channel was closed",
296295
)));
297296
}

examples/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ hickory-resolver = { workspace = true }
1515
log = { workspace = true }
1616
mio = { workspace = true }
1717
rcgen = { workspace = true }
18-
watfaq-rustls = { path = "../rustls", features = [ "logging" ]}
18+
watfaq-rustls = { path = "../rustls", features = [ "logging" ] }
1919
serde = { workspace = true }
2020
tokio = { workspace = true }
2121
webpki-roots = { workspace = true }

examples/src/bin/reality-client.rs

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,10 @@ fn main() {
3838
// Parse command line arguments
3939
let args: Vec<String> = env::args().collect();
4040
if args.len() != 5 {
41-
eprintln!("Usage: {} <server_addr> <sni_servername> <public_key_base64> <short_id_hex>", args[0]);
41+
eprintln!(
42+
"Usage: {} <server_addr> <sni_servername> <public_key_base64> <short_id_hex>",
43+
args[0]
44+
);
4245
eprintln!();
4346
eprintln!("Parameters:");
4447
eprintln!(" <server_addr> Real server address (e.g., tw04.ctg.wtf:443)");
@@ -101,11 +104,10 @@ fn main() {
101104
let short_id_len = short_id.len();
102105

103106
// Create Reality configuration
104-
let reality_config = RealityConfig::new(server_pubkey, short_id)
105-
.unwrap_or_else(|e| {
106-
eprintln!("Error creating Reality config: {}", e);
107-
std::process::exit(1);
108-
});
107+
let reality_config = RealityConfig::new(server_pubkey, short_id).unwrap_or_else(|e| {
108+
eprintln!("Error creating Reality config: {}", e);
109+
std::process::exit(1);
110+
});
109111

110112
println!("Reality configuration created successfully");
111113
println!(" Server public key: {}", bytes_to_hex(&server_pubkey));
@@ -129,7 +131,10 @@ fn main() {
129131
// Allow using SSLKEYLOGFILE for debugging
130132
config.key_log = Arc::new(watfaq_rustls::KeyLogFile::new());
131133

132-
println!("\nConnecting to {} (SNI: {})...", &server_addr, &sni_servername);
134+
println!(
135+
"\nConnecting to {} (SNI: {})...",
136+
&server_addr, &sni_servername
137+
);
133138

134139
// Use SNI servername for TLS connection (for disguise/camouflage)
135140
let server_name: pki_types::ServerName<'static> = sni_servername
@@ -191,34 +196,35 @@ fn main() {
191196
println!("\nServer response:");
192197
println!("----------------------------------------");
193198
let mut plaintext = Vec::new();
194-
tls.read_to_end(&mut plaintext).unwrap_or_else(|e| {
195-
eprintln!("Error reading response: {}", e);
196-
std::process::exit(1);
197-
});
199+
tls.read_to_end(&mut plaintext)
200+
.unwrap_or_else(|e| {
201+
eprintln!("Error reading response: {}", e);
202+
std::process::exit(1);
203+
});
198204
stdout().write_all(&plaintext).unwrap();
199205
println!("----------------------------------------");
200206
println!("\nConnection closed successfully");
201207
}
202208

203209
/// Helper function to convert hex string to bytes
204210
fn hex_to_bytes(hex: &str) -> Result<Vec<u8>, &'static str> {
205-
if hex.len() % 2 != 0 {
211+
if !hex.len().is_multiple_of(2) {
206212
return Err("Hex string must have even length");
207213
}
208214

209215
let mut bytes = Vec::new();
210216
for i in (0..hex.len()).step_by(2) {
211217
let byte_str = &hex[i..i + 2];
212-
let byte = u8::from_str_radix(byte_str, 16)
213-
.map_err(|_| "Invalid hex character")?;
218+
let byte = u8::from_str_radix(byte_str, 16).map_err(|_| "Invalid hex character")?;
214219
bytes.push(byte);
215220
}
216221
Ok(bytes)
217222
}
218223

219224
/// Helper function to convert bytes to hex string
220225
fn bytes_to_hex(bytes: &[u8]) -> String {
221-
bytes.iter()
226+
bytes
227+
.iter()
222228
.map(|b| format!("{:02x}", b))
223229
.collect::<Vec<_>>()
224230
.join("")

examples/src/bin/server_acceptor.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ impl TestPki {
229229
&self,
230230
serials: Vec<rcgen::SerialNumber>,
231231
next_update_seconds: u64,
232-
) -> CertificateRevocationListDer {
232+
) -> CertificateRevocationListDer<'_> {
233233
// In a real use-case you would want to set this to the current date/time.
234234
let now = rcgen::date_time_ymd(2023, 1, 1);
235235

rustls/build.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
/// for Rust Nightly.
33
///
44
/// See the comment in lib.rs to understand why we need this.
5-
65
#[cfg_attr(feature = "read_buf", rustversion::not(nightly))]
76
fn main() {
87
println!("cargo:rustc-check-cfg=cfg(bench)");

rustls/src/client/hs.rs

Lines changed: 48 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@ use core::ops::Deref;
77

88
use pki_types::ServerName;
99

10+
use super::reality;
1011
#[cfg(feature = "tls12")]
1112
use super::tls12;
1213
use super::Tls12Resumption;
13-
use super::reality;
1414
#[cfg(feature = "logging")]
1515
use crate::bs_debug;
1616
use crate::check::inappropriate_handshake_message;
@@ -132,7 +132,7 @@ where
132132
// Set kx_state to X25519 group for Reality
133133
let x25519_group = config
134134
.find_kx_group(NamedGroup::X25519, ProtocolVersion::TLSv1_3)
135-
.expect("X25519 group required for Reality");
135+
.ok_or(Error::General("X25519 group required for Reality".into()))?;
136136
cx.common.kx_state = KxState::Start(x25519_group);
137137
None // Will be set later from reality_state
138138
} else if config.supports_version(ProtocolVersion::TLSv1_3) {
@@ -171,7 +171,7 @@ where
171171
}
172172
Some(inner.session_id)
173173
}
174-
_ => None,
174+
_ => None::<SessionId>,
175175
}
176176
} else {
177177
debug!("Not resuming any session");
@@ -235,6 +235,7 @@ struct ExpectServerHello {
235235
offered_key_share: Option<Box<dyn ActiveKeyExchange>>,
236236
suite: Option<SupportedCipherSuite>,
237237
ech_state: Option<EchState>,
238+
reality_state: Option<reality::RealitySessionState>,
238239
}
239240

240241
struct ExpectServerHelloOrHelloRetryRequest {
@@ -552,6 +553,47 @@ where
552553
payload: HandshakePayload::ClientHello(chp_payload),
553554
};
554555

556+
// Compute Reality session_id BEFORE PSK binder to avoid invalidating the binder
557+
// Reality uses ClientHello with session_id=0 as AAD, so this order is safe
558+
if let Some(ref reality) = reality_state {
559+
// Step 1: Set session_id to zero temporarily
560+
let mut buffer = Vec::new();
561+
match &mut chp.payload {
562+
HandshakePayload::ClientHello(c) => {
563+
c.session_id = SessionId {
564+
len: 32,
565+
data: [0; 32],
566+
};
567+
}
568+
_ => unreachable!(),
569+
}
570+
571+
// Step 2: Encode ClientHello with zero session_id (for AAD)
572+
chp.encode(&mut buffer);
573+
574+
// Step 3: Get HKDF-SHA256 provider
575+
let hkdf = reality::get_hkdf_sha256_from_config(&config.provider.cipher_suites)?;
576+
577+
// Step 4: Compute Reality session_id
578+
let session_id_data = reality.compute_session_id(
579+
&input.random,
580+
&buffer,
581+
hkdf,
582+
config.time_provider.as_ref(),
583+
)?;
584+
585+
// Step 5: Update session_id with computed Reality value
586+
match &mut chp.payload {
587+
HandshakePayload::ClientHello(c) => {
588+
c.session_id = SessionId {
589+
len: 32,
590+
data: session_id_data,
591+
};
592+
}
593+
_ => unreachable!(),
594+
}
595+
}
596+
555597
let early_key_schedule = match (ech_state.as_mut(), tls13_session) {
556598
// If we're performing ECH and resuming, then the PSK binder will have been dealt with
557599
// separately, and we need to take the early_data_key_schedule computed for the inner hello.
@@ -561,7 +603,7 @@ where
561603
.map(|schedule| (tls13_session.suite(), schedule)),
562604

563605
// When we're not doing ECH and resuming, then the PSK binder need to be filled in as
564-
// normal.
606+
// normal. Reality session_id has been set above, so PSK binder will see the correct value.
565607
(_, Some(tls13_session)) => Some((
566608
tls13_session.suite(),
567609
tls13::fill_in_psk_binder(&tls13_session, &transcript_buffer, &mut chp),
@@ -596,46 +638,6 @@ where
596638
}
597639
}
598640

599-
// Compute Reality session_id if Reality is enabled
600-
if let Some(ref reality) = reality_state {
601-
// Step 1: Set session_id to zero temporarily
602-
let mut buffer = Vec::new();
603-
match &mut chp.payload {
604-
HandshakePayload::ClientHello(c) => {
605-
c.session_id = SessionId {
606-
len: 32,
607-
data: [0; 32],
608-
};
609-
}
610-
_ => unreachable!(),
611-
}
612-
613-
// Step 2: Encode ClientHello with zero session_id
614-
chp.encode(&mut buffer);
615-
616-
// Step 3: Get HKDF-SHA256 provider
617-
let hkdf = reality::get_hkdf_sha256_from_config(&config.provider.cipher_suites)?;
618-
619-
// Step 4: Compute Reality session_id
620-
let session_id_data = reality.compute_session_id(
621-
&input.random,
622-
&buffer,
623-
hkdf,
624-
config.time_provider.as_ref(),
625-
)?;
626-
627-
// Step 5: Update session_id
628-
match &mut chp.payload {
629-
HandshakePayload::ClientHello(c) => {
630-
c.session_id = SessionId {
631-
len: 32,
632-
data: session_id_data,
633-
};
634-
}
635-
_ => unreachable!(),
636-
}
637-
}
638-
639641
let ch = Message {
640642
version: match retryreq {
641643
// <https://datatracker.ietf.org/doc/html/rfc8446#section-5.1>:
@@ -698,6 +700,7 @@ where
698700
offered_key_share: key_share,
699701
suite,
700702
ech_state,
703+
reality_state,
701704
};
702705

703706
Ok(if support_tls13 && retryreq.is_none() {
@@ -1266,7 +1269,7 @@ impl ExpectServerHelloOrHelloRetryRequest {
12661269
self.next.input,
12671270
cx,
12681271
self.next.ech_state,
1269-
None, // Reality state not used in retry
1272+
self.next.reality_state,
12701273
)
12711274
}
12721275
}

0 commit comments

Comments
 (0)