1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
|
//! This is a simple client using rustls' unbuffered API. Meaning that the application layer must
//! handle the buffers required to receive, process and send TLS data.
use std::error::Error;
use std::io::{Read, Write};
use std::net::TcpStream;
use std::sync::Arc;
use rustls::client::{ClientConnectionData, EarlyDataError, UnbufferedClientConnection};
use rustls::unbuffered::{
AppDataRecord, ConnectionState, EncodeError, EncryptError, InsufficientSizeError,
UnbufferedStatus, WriteTraffic,
};
use rustls::version::TLS13;
use rustls::{ClientConfig, RootCertStore};
use rustls_native_certs::load_native_certs;
fn main() -> Result<(), Box<dyn Error>> {
let mut root_store = RootCertStore::empty();
for cert in load_native_certs().expect("could not load platform certs") {
root_store.add(cert)
.expect("could not add certificate");
};
let mut config = ClientConfig::builder_with_protocol_versions(&[&TLS13])
.with_root_certificates(root_store)
.with_no_client_auth();
config.enable_early_data = SEND_EARLY_DATA;
let config = Arc::new(config);
let mut incoming_tls = vec![0; INCOMING_TLS_BUFSIZE];
let mut outgoing_tls = vec![0; OUTGOING_TLS_INITIAL_BUFSIZE];
converse(&config, false, &mut incoming_tls, &mut outgoing_tls)?;
if SEND_EARLY_DATA {
eprintln!("---- second connection ----");
converse(&config, true, &mut incoming_tls, &mut outgoing_tls)?;
}
Ok(())
}
fn converse(
config: &Arc<ClientConfig>,
send_early_data: bool,
incoming_tls: &mut [u8],
outgoing_tls: &mut Vec<u8>,
) -> Result<(), Box<dyn Error>> {
let mut conn = UnbufferedClientConnection::new(config.clone(), SERVER_NAME.try_into()?)?;
let mut sock = TcpStream::connect(format!("{SERVER_NAME}:{PORT}"))?;
let mut incoming_used = 0;
let mut outgoing_used = 0;
let mut we_closed = false;
let mut fully_closed = false;
let mut sent_request = false;
let mut received_response = false;
let mut sent_early_data = false;
let mut iter_count = 0;
while !fully_closed {
let UnbufferedStatus { mut discard, state } =
conn.process_tls_records(&mut incoming_tls[..incoming_used]);
match dbg!(state.unwrap()) {
ConnectionState::ReadTraffic(mut state) => {
while let Some(res) = state.next_record() {
let AppDataRecord {
discard: new_discard,
payload,
} = res?;
discard += new_discard;
if payload.starts_with(b"HTTP") {
let response = core::str::from_utf8(payload)?;
let header = response
.lines()
.next()
.unwrap_or(response);
println!("{header}");
} else {
println!("(.. continued HTTP response ..)");
}
received_response = true;
}
}
ConnectionState::EncodeTlsData(mut state) => {
try_or_resize_and_retry(
|out_buffer| state.encode(out_buffer),
|e| {
if let EncodeError::InsufficientSize(is) = &e {
Ok(*is)
} else {
Err(e.into())
}
},
outgoing_tls,
&mut outgoing_used,
)?;
}
ConnectionState::TransmitTlsData(mut state) => {
if let Some(mut may_encrypt_early_data) = state.may_encrypt_early_data() {
let written = try_or_resize_and_retry(
|out_buffer| may_encrypt_early_data.encrypt(EARLY_DATA, out_buffer),
|e| match &e {
EarlyDataError::Encrypt(EncryptError::InsufficientSize(is)) => Ok(*is),
_ => Err(e.into()),
},
outgoing_tls,
&mut outgoing_used,
)?;
eprintln!("queued {written}B of early data");
sent_early_data = true;
}
if let Some(mut may_encrypt) = state.may_encrypt_app_data() {
encrypt_http_request(
&mut sent_request,
&mut may_encrypt,
outgoing_tls,
&mut outgoing_used,
);
}
send_tls(&mut sock, outgoing_tls, &mut outgoing_used)?;
state.done();
}
ConnectionState::BlockedHandshake { .. } => {
recv_tls(&mut sock, incoming_tls, &mut incoming_used)?;
}
ConnectionState::WriteTraffic(mut may_encrypt) => {
if encrypt_http_request(
&mut sent_request,
&mut may_encrypt,
outgoing_tls,
&mut outgoing_used,
) {
send_tls(&mut sock, outgoing_tls, &mut outgoing_used)?;
recv_tls(&mut sock, incoming_tls, &mut incoming_used)?;
} else if !received_response {
// this happens in the TLS 1.3 case. the app-data was sent in the preceding
// `TransmitTlsData` state. the server should have already written a
// response which we can read out from the socket
recv_tls(&mut sock, incoming_tls, &mut incoming_used)?;
} else if !we_closed {
try_or_resize_and_retry(
|out_buffer| may_encrypt.queue_close_notify(out_buffer),
|e| {
if let EncryptError::InsufficientSize(is) = &e {
Ok(*is)
} else {
Err(e.into())
}
},
outgoing_tls,
&mut outgoing_used,
)?;
send_tls(&mut sock, outgoing_tls, &mut outgoing_used)?;
we_closed = true;
} else {
recv_tls(&mut sock, incoming_tls, &mut incoming_used)?;
}
}
ConnectionState::PeerClosed => {}
ConnectionState::Closed => {
fully_closed = true;
}
// other states are not expected in this example
_ => unreachable!(),
}
if discard != 0 {
assert!(discard <= incoming_used);
incoming_tls.copy_within(discard..incoming_used, 0);
incoming_used -= discard;
eprintln!("discarded {discard}B from `incoming_tls`");
}
iter_count += 1;
assert!(
iter_count < MAX_ITERATIONS,
"did not get a HTTP response within {MAX_ITERATIONS} iterations"
);
}
assert!(sent_request);
assert!(received_response);
assert_eq!(send_early_data, sent_early_data);
assert_eq!(0, incoming_used);
assert_eq!(0, outgoing_used);
Ok(())
}
fn try_or_resize_and_retry<E>(
mut f: impl FnMut(&mut [u8]) -> Result<usize, E>,
map_err: impl FnOnce(E) -> Result<InsufficientSizeError, Box<dyn Error>>,
outgoing_tls: &mut Vec<u8>,
outgoing_used: &mut usize,
) -> Result<usize, Box<dyn Error>>
where
E: Error + 'static,
{
let written = match f(&mut outgoing_tls[*outgoing_used..]) {
Ok(written) => written,
Err(e) => {
let InsufficientSizeError { required_size } = map_err(e)?;
let new_len = *outgoing_used + required_size;
outgoing_tls.resize(new_len, 0);
eprintln!("resized `outgoing_tls` buffer to {new_len}B");
f(&mut outgoing_tls[*outgoing_used..])?
}
};
*outgoing_used += written;
Ok(written)
}
fn recv_tls(
sock: &mut TcpStream,
incoming_tls: &mut [u8],
incoming_used: &mut usize,
) -> Result<(), Box<dyn Error>> {
let read = sock.read(&mut incoming_tls[*incoming_used..])?;
eprintln!("received {read}B of data");
*incoming_used += read;
Ok(())
}
fn send_tls(
sock: &mut TcpStream,
outgoing_tls: &[u8],
outgoing_used: &mut usize,
) -> Result<(), Box<dyn Error>> {
sock.write_all(&outgoing_tls[..*outgoing_used])?;
eprintln!("sent {outgoing_used}B of data");
*outgoing_used = 0;
Ok(())
}
fn encrypt_http_request(
sent_request: &mut bool,
may_encrypt: &mut WriteTraffic<'_, ClientConnectionData>,
outgoing_tls: &mut [u8],
outgoing_used: &mut usize,
) -> bool {
if !*sent_request {
let request = format!("GET / HTTP/1.1\r\nHost: {SERVER_NAME}\r\nConnection: close\r\nAccept-Encoding: identity\r\n\r\n").into_bytes();
let written = may_encrypt
.encrypt(&request, &mut outgoing_tls[*outgoing_used..])
.expect("encrypted request does not fit in `outgoing_tls`");
*outgoing_used += written;
*sent_request = true;
eprintln!("queued HTTP request");
true
} else {
false
}
}
const SERVER_NAME: &str = "example.com";
const PORT: u16 = 443;
const KB: usize = 1024;
const INCOMING_TLS_BUFSIZE: usize = 16 * KB;
const OUTGOING_TLS_INITIAL_BUFSIZE: usize = KB;
const MAX_ITERATIONS: usize = 20;
const SEND_EARLY_DATA: bool = false;
const EARLY_DATA: &[u8] = b"hello";
|