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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
use async_compat::CompatExt;
use distant_core::{
Request, Session, SessionChannelExt, SessionDetails, SessionInfo, Transport,
XChaCha20Poly1305Codec,
};
use log::*;
use smol::channel::Receiver as SmolReceiver;
use std::{
collections::BTreeMap,
fmt,
io::{self, Write},
net::{IpAddr, SocketAddr},
path::PathBuf,
sync::Arc,
time::Duration,
};
use tokio::sync::{mpsc, Mutex};
use wezterm_ssh::{Config as WezConfig, Session as WezSession, SessionEvent as WezSessionEvent};
mod handler;
mod process;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
pub enum SshBackend {
LibSsh,
Ssh2,
}
impl Default for SshBackend {
fn default() -> Self {
Self::Ssh2
}
}
impl fmt::Display for SshBackend {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::LibSsh => write!(f, "libssh"),
Self::Ssh2 => write!(f, "ssh2"),
}
}
}
#[derive(Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Ssh2AuthPrompt {
pub prompt: String,
pub echo: bool,
}
#[derive(Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Ssh2AuthEvent {
pub username: String,
pub instructions: String,
pub prompts: Vec<Ssh2AuthPrompt>,
}
#[derive(Clone, Debug, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct Ssh2SessionOpts {
pub backend: SshBackend,
pub identity_files: Vec<PathBuf>,
pub identities_only: Option<bool>,
pub port: Option<u16>,
pub proxy_command: Option<String>,
pub user: Option<String>,
pub user_known_hosts_files: Vec<PathBuf>,
pub verbose: bool,
pub other: BTreeMap<String, String>,
}
#[derive(Clone, Debug)]
pub struct IntoDistantSessionOpts {
pub binary: String,
pub args: String,
pub use_login_shell: bool,
pub timeout: Duration,
}
impl Default for IntoDistantSessionOpts {
fn default() -> Self {
Self {
binary: String::from("distant"),
args: String::new(),
use_login_shell: false,
timeout: Duration::from_secs(15),
}
}
}
pub struct Ssh2AuthHandler<'a> {
pub on_authenticate: Box<dyn FnMut(Ssh2AuthEvent) -> io::Result<Vec<String>> + 'a>,
pub on_banner: Box<dyn FnMut(&str) + 'a>,
pub on_host_verify: Box<dyn FnMut(&str) -> io::Result<bool> + 'a>,
pub on_error: Box<dyn FnMut(&str) + 'a>,
}
impl Default for Ssh2AuthHandler<'static> {
fn default() -> Self {
Self {
on_authenticate: Box::new(|ev| {
if !ev.username.is_empty() {
eprintln!("Authentication for {}", ev.username);
}
if !ev.instructions.is_empty() {
eprintln!("{}", ev.instructions);
}
let mut answers = Vec::new();
for prompt in &ev.prompts {
let mut prompt_lines = prompt.prompt.split('\n').collect::<Vec<_>>();
let prompt_line = prompt_lines.pop().unwrap();
for line in prompt_lines.into_iter() {
eprintln!("{}", line);
}
let answer = if prompt.echo {
eprint!("{}", prompt_line);
std::io::stderr().lock().flush()?;
let mut answer = String::new();
std::io::stdin().read_line(&mut answer)?;
answer
} else {
rpassword::prompt_password_stderr(prompt_line)?
};
answers.push(answer);
}
Ok(answers)
}),
on_banner: Box::new(|_| {}),
on_host_verify: Box::new(|message| {
eprintln!("{}", message);
match rpassword::prompt_password_stderr("Enter [y/N]> ")?.as_str() {
"y" | "Y" | "yes" | "YES" => Ok(true),
_ => Ok(false),
}
}),
on_error: Box::new(|_| {}),
}
}
}
pub struct Ssh2Session {
session: WezSession,
events: SmolReceiver<WezSessionEvent>,
host: String,
port: u16,
authenticated: bool,
}
impl Ssh2Session {
pub fn connect(host: impl AsRef<str>, opts: Ssh2SessionOpts) -> io::Result<Self> {
debug!(
"Establishing ssh connection to {} using {:?}",
host.as_ref(),
opts
);
let mut config = WezConfig::new();
config.add_default_config_files();
let mut config = config.for_host(host.as_ref());
if let Some(port) = opts.port.as_ref() {
config.insert("port".to_string(), port.to_string());
}
if let Some(user) = opts.user.as_ref() {
config.insert("user".to_string(), user.to_string());
}
if !opts.identity_files.is_empty() {
config.insert(
"identityfile".to_string(),
opts.identity_files
.iter()
.filter_map(|p| p.to_str())
.map(ToString::to_string)
.collect::<Vec<String>>()
.join(" "),
);
}
if let Some(yes) = opts.identities_only.as_ref() {
let value = if *yes {
"yes".to_string()
} else {
"no".to_string()
};
config.insert("identitiesonly".to_string(), value);
}
if let Some(cmd) = opts.proxy_command.as_ref() {
config.insert("proxycommand".to_string(), cmd.to_string());
}
if !opts.user_known_hosts_files.is_empty() {
config.insert(
"userknownhostsfile".to_string(),
opts.user_known_hosts_files
.iter()
.filter_map(|p| p.to_str())
.map(ToString::to_string)
.collect::<Vec<String>>()
.join(" "),
);
}
config.insert("wezterm_ssh_verbose".to_string(), opts.verbose.to_string());
config.insert("wezterm_ssh_backend".to_string(), opts.backend.to_string());
config.extend(opts.other);
let port = config
.get("port")
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "Missing port"))?
.parse::<u16>()
.map_err(|x| io::Error::new(io::ErrorKind::InvalidData, x))?;
trace!("WezSession::connect({:?})", config);
let (session, events) =
WezSession::connect(config).map_err(|x| io::Error::new(io::ErrorKind::Other, x))?;
Ok(Self {
session,
events,
host: host.as_ref().to_string(),
port,
authenticated: false,
})
}
pub fn host(&self) -> &str {
&self.host
}
pub fn port(&self) -> u16 {
self.port
}
#[inline]
pub fn is_authenticated(&self) -> bool {
self.authenticated
}
pub async fn authenticate(&mut self, mut handler: Ssh2AuthHandler<'_>) -> io::Result<()> {
if self.authenticated {
return Ok(());
}
while let Ok(event) = self.events.recv().await {
match event {
WezSessionEvent::Banner(banner) => {
if let Some(banner) = banner {
(handler.on_banner)(banner.as_ref());
}
}
WezSessionEvent::HostVerify(verify) => {
let verified = (handler.on_host_verify)(verify.message.as_str())?;
verify
.answer(verified)
.compat()
.await
.map_err(|x| io::Error::new(io::ErrorKind::Other, x))?;
}
WezSessionEvent::Authenticate(mut auth) => {
let ev = Ssh2AuthEvent {
username: auth.username.clone(),
instructions: auth.instructions.clone(),
prompts: auth
.prompts
.drain(..)
.map(|p| Ssh2AuthPrompt {
prompt: p.prompt,
echo: p.echo,
})
.collect(),
};
let answers = (handler.on_authenticate)(ev)?;
auth.answer(answers)
.compat()
.await
.map_err(|x| io::Error::new(io::ErrorKind::Other, x))?;
}
WezSessionEvent::Error(err) => {
(handler.on_error)(&err);
return Err(io::Error::new(io::ErrorKind::PermissionDenied, err));
}
WezSessionEvent::Authenticated => break,
}
}
self.authenticated = true;
Ok(())
}
pub async fn into_distant_session(self, opts: IntoDistantSessionOpts) -> io::Result<Session> {
if !self.authenticated {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"Not authenticated",
));
}
let timeout = opts.timeout;
let mut candidate_ips = tokio::net::lookup_host(format!("{}:{}", self.host, self.port))
.await
.map_err(|x| {
io::Error::new(
x.kind(),
format!("{} needs to be resolvable outside of ssh: {}", self.host, x),
)
})?
.into_iter()
.map(|addr| addr.ip())
.collect::<Vec<IpAddr>>();
candidate_ips.sort_unstable();
candidate_ips.dedup();
if candidate_ips.is_empty() {
return Err(io::Error::new(
io::ErrorKind::AddrNotAvailable,
format!("Unable to resolve {}:{}", self.host, self.port),
));
}
let info = self.into_distant_session_info(opts).await?;
let key = info.key;
let codec = XChaCha20Poly1305Codec::from(key);
let mut err = None;
for ip in candidate_ips {
let addr = SocketAddr::new(ip, info.port);
debug!("Attempting to connect to distant server @ {}", addr);
match Session::tcp_connect_timeout(addr, codec.clone(), timeout).await {
Ok(session) => return Ok(session),
Err(x) => err = Some(x),
}
}
Err(err.expect("Err set above"))
}
pub async fn into_distant_session_info(
self,
opts: IntoDistantSessionOpts,
) -> io::Result<SessionInfo> {
if !self.authenticated {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"Not authenticated",
));
}
let host = self.host().to_string();
let mut session = self.into_ssh_client_session().await?;
let mut args = vec![
String::from("listen"),
String::from("--host"),
String::from("ssh"),
];
args.extend(
shell_words::split(&opts.args)
.map_err(|x| io::Error::new(io::ErrorKind::InvalidInput, x))?,
);
let (bin, args) = if opts.use_login_shell {
(
String::from("sh"),
vec![
String::from("-c"),
shell_words::quote(&format!(
"echo {} {} | $SHELL -l",
opts.binary,
args.join(" ")
))
.to_string(),
],
)
} else {
(opts.binary, args)
};
debug!("Executing {} {}", bin, args.join(" "));
let mut proc = session
.spawn("<ssh-launch>", bin, args, true, None)
.await
.map_err(|x| io::Error::new(io::ErrorKind::Other, x))?;
let mut stdout = proc.stdout.take().unwrap();
let mut stderr = proc.stderr.take().unwrap();
let (success, code) = proc
.wait()
.await
.map_err(|x| io::Error::new(io::ErrorKind::BrokenPipe, x))?;
session.abort();
let _ = session.wait().await;
let mut output = Vec::new();
if success {
while let Ok(data) = stdout.read().await {
output.extend(&data);
}
let maybe_info = output
.split(|&b| b == b'\n')
.map(String::from_utf8_lossy)
.find_map(|line| line.parse::<SessionInfo>().ok());
match maybe_info {
Some(mut info) => {
info.host = host;
Ok(info)
}
None => Err(io::Error::new(
io::ErrorKind::InvalidData,
"Missing session data",
)),
}
} else {
while let Ok(data) = stderr.read().await {
output.extend(&data);
}
Err(io::Error::new(
io::ErrorKind::Other,
format!(
"Spawning distant failed [{}]: {}",
code.map(|x| x.to_string())
.unwrap_or_else(|| String::from("???")),
match String::from_utf8(output) {
Ok(output) => output,
Err(x) => x.to_string(),
}
),
))
}
}
pub async fn into_ssh_client_session(self) -> io::Result<Session> {
if !self.authenticated {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"Not authenticated",
));
}
let (t1, t2) = Transport::pair(1);
let tag = format!("ssh {}:{}", self.host, self.port);
let session = Session::initialize_with_details(t1, Some(SessionDetails::Custom { tag }))?;
let (mut t_read, mut t_write) = t2.into_split();
let Self {
session: wez_session,
..
} = self;
let (tx, mut rx) = mpsc::channel(1);
tokio::spawn(async move {
let state = Arc::new(Mutex::new(handler::State::default()));
while let Ok(Some(req)) = t_read.receive::<Request>().await {
if let Err(x) =
handler::process(wez_session.clone(), Arc::clone(&state), req, tx.clone()).await
{
error!("Ssh session receiver handler failed: {}", x);
}
}
debug!("Ssh receiver task is now closed");
});
tokio::spawn(async move {
while let Some(res) = rx.recv().await {
if let Err(x) = t_write.send(res).await {
error!("Ssh session sender failed: {}", x);
break;
}
}
debug!("Ssh sender task is now closed");
});
Ok(session)
}
}