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
|
use super::config::{WS_CONTROL_ENDPOINT, WS_TERMINAL_ENDPOINT};
use super::http_client::HttpClientWithCookies;
use std::path::Path;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio::net::TcpStream;
use tokio_tungstenite::WebSocketStream;
// -- MaybeTls stream enum -------------------------------------------------
/// A TCP stream that may or may not be wrapped in TLS.
pub enum MaybeTls {
Plain(TcpStream),
Tls(tokio_rustls::client::TlsStream<TcpStream>),
}
impl AsyncRead for MaybeTls {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<std::io::Result<()>> {
match self.get_mut() {
MaybeTls::Plain(s) => Pin::new(s).poll_read(cx, buf),
MaybeTls::Tls(s) => Pin::new(s).poll_read(cx, buf),
}
}
}
impl AsyncWrite for MaybeTls {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
match self.get_mut() {
MaybeTls::Plain(s) => Pin::new(s).poll_write(cx, buf),
MaybeTls::Tls(s) => Pin::new(s).poll_write(cx, buf),
}
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
match self.get_mut() {
MaybeTls::Plain(s) => Pin::new(s).poll_flush(cx),
MaybeTls::Tls(s) => Pin::new(s).poll_flush(cx),
}
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
match self.get_mut() {
MaybeTls::Plain(s) => Pin::new(s).poll_shutdown(cx),
MaybeTls::Tls(s) => Pin::new(s).poll_shutdown(cx),
}
}
}
// -- NoVerifier (for --insecure mode) --------------------------------------
#[derive(Debug)]
struct NoVerifier;
impl rustls::client::danger::ServerCertVerifier for NoVerifier {
fn verify_server_cert(
&self,
_end_entity: &rustls_pki_types::CertificateDer<'_>,
_intermediates: &[rustls_pki_types::CertificateDer<'_>],
_server_name: &rustls_pki_types::ServerName<'_>,
_ocsp_response: &[u8],
_now: rustls_pki_types::UnixTime,
) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
Ok(rustls::client::danger::ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
_message: &[u8],
_cert: &rustls_pki_types::CertificateDer<'_>,
_dss: &rustls::DigitallySignedStruct,
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
}
fn verify_tls13_signature(
&self,
_message: &[u8],
_cert: &rustls_pki_types::CertificateDer<'_>,
_dss: &rustls::DigitallySignedStruct,
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
}
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
rustls::crypto::aws_lc_rs::default_provider()
.signature_verification_algorithms
.supported_schemes()
}
}
// -- TLS config builder ----------------------------------------------------
fn build_tls_config(
ca_cert: Option<&Path>,
insecure: bool,
) -> Result<Arc<rustls::ClientConfig>, Box<dyn std::error::Error>> {
let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
if insecure {
let config = rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()?
.dangerous()
.with_custom_certificate_verifier(Arc::new(NoVerifier))
.with_no_client_auth();
Ok(Arc::new(config))
} else if let Some(ca_path) = ca_cert {
let ca_pem = std::fs::read(ca_path)?;
let mut cursor = std::io::Cursor::new(ca_pem);
let certs: Vec<rustls_pki_types::CertificateDer<'static>> =
rustls_pemfile::certs(&mut cursor)
.filter_map(|r| r.ok())
.collect();
let mut root_store = rustls::RootCertStore::empty();
for cert in certs {
root_store.add(cert)?;
}
let config = rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()?
.with_root_certificates(root_store)
.with_no_client_auth();
Ok(Arc::new(config))
} else {
let native_certs = rustls_native_certs::load_native_certs();
for err in &native_certs.errors {
log::warn!("Error loading native certificate: {}", err);
}
let mut root_store = rustls::RootCertStore::empty();
root_store.add_parsable_certificates(native_certs.certs);
let config = rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()?
.with_root_certificates(root_store)
.with_no_client_auth();
Ok(Arc::new(config))
}
}
// -- WebSocket connection helpers ------------------------------------------
async fn connect_ws(
request: tokio_tungstenite::tungstenite::http::Request<()>,
host: &str,
port: u16,
tls_config: Option<Arc<rustls::ClientConfig>>,
) -> Result<WebSocketStream<MaybeTls>, Box<dyn std::error::Error>> {
let tcp_stream = TcpStream::connect((host, port)).await?;
let stream = if let Some(config) = tls_config {
let connector = tokio_rustls::TlsConnector::from(config);
let server_name = rustls_pki_types::ServerName::try_from(host.to_string())?;
let tls_stream = connector.connect(server_name, tcp_stream).await?;
MaybeTls::Tls(tls_stream)
} else {
MaybeTls::Plain(tcp_stream)
};
let (ws_stream, _response) =
tokio_tungstenite::client_async_with_config(request, stream, None).await?;
Ok(ws_stream)
}
// -- Public API ------------------------------------------------------------
pub struct WebSocketConnections {
pub terminal_ws: WebSocketStream<MaybeTls>,
pub control_ws: WebSocketStream<MaybeTls>,
pub web_client_id: String,
}
impl std::fmt::Debug for WebSocketConnections {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WebSocketConnections")
.field("web_client_id", &self.web_client_id)
.finish()
}
}
pub async fn establish_websocket_connections(
web_client_id: &str,
http_client: &HttpClientWithCookies,
server_base_url: &str,
session_name: &str,
ca_cert: Option<&Path>,
insecure: bool,
) -> Result<WebSocketConnections, Box<dyn std::error::Error>> {
let parsed_url = url::Url::parse(server_base_url)?;
let host = parsed_url
.host_str()
.ok_or("no host in server URL")?
.to_string();
let port = parsed_url
.port_or_known_default()
.ok_or("no port in server URL")?;
let is_tls = parsed_url.scheme() == "https";
let ws_protocol = if is_tls { "wss" } else { "ws" };
let base_host = format!("{}:{}", host, port);
let terminal_url = if session_name.is_empty() {
format!(
"{}://{}{WS_TERMINAL_ENDPOINT}?web_client_id={}",
ws_protocol,
base_host,
urlencoding::encode(web_client_id)
)
} else {
format!(
"{}://{}{WS_TERMINAL_ENDPOINT}/{}?web_client_id={}",
ws_protocol,
base_host,
urlencoding::encode(session_name),
urlencoding::encode(web_client_id)
)
};
let control_url = format!("{}://{}{WS_CONTROL_ENDPOINT}", ws_protocol, base_host);
log::info!("Connecting to terminal WebSocket: {}", terminal_url);
log::info!("Connecting to control WebSocket: {}", control_url);
// Build WebSocket requests with cookies
let mut terminal_request = tokio_tungstenite::tungstenite::http::Request::builder()
.uri(&terminal_url)
.header("Host", &base_host)
.header("Upgrade", "websocket")
.header("Connection", "Upgrade")
.header(
"Sec-WebSocket-Key",
tokio_tungstenite::tungstenite::handshake::client::generate_key(),
)
.header("Sec-WebSocket-Version", "13");
let mut control_request = tokio_tungstenite::tungstenite::http::Request::builder()
.uri(&control_url)
.header("Host", &base_host)
.header("Upgrade", "websocket")
.header("Connection", "Upgrade")
.header(
"Sec-WebSocket-Key",
tokio_tungstenite::tungstenite::handshake::client::generate_key(),
)
.header("Sec-WebSocket-Version", "13");
// Add cookies if available
if let Some(cookie_header) = http_client.get_cookie_header() {
terminal_request = terminal_request.header("Cookie", &cookie_header);
control_request = control_request.header("Cookie", &cookie_header);
}
let terminal_request = terminal_request.body(())?;
let control_request = control_request.body(())?;
// Build TLS config (only for wss://)
let tls_config = if is_tls {
Some(build_tls_config(ca_cert, insecure)?)
} else {
None
};
// Connect to both WebSockets
let terminal_ws = connect_ws(terminal_request, &host, port, tls_config.clone()).await?;
let control_ws = connect_ws(control_request, &host, port, tls_config).await?;
Ok(WebSocketConnections {
terminal_ws,
control_ws,
web_client_id: web_client_id.to_owned(),
})
}
|