1use crate::error::{NetconfClientError, NetconfClientResult};
4use crate::framer::Framer;
5use crate::framer::async_framer::AsyncFramer;
6use crate::transport::Transport;
7use async_trait::async_trait;
8use core::fmt;
9use core::time::Duration;
10use log::{debug, trace, warn};
11use russh::client::{self, Handle};
12use russh::keys::agent::AgentIdentity;
13use russh::keys::agent::client::AgentClient;
14use russh::keys::{
15 self, HashAlg, PrivateKeyWithHashAlg, PublicKey, PublicKeyOrCertificate, known_hosts,
16};
17use russh::{Channel, ChannelMsg, ChannelStream, Disconnect, Preferred};
18use std::borrow::Cow;
19use std::path::{Path, PathBuf};
20use std::sync::Arc;
21use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt};
22use tokio::net::TcpStream;
23use tokio::time::timeout;
24use zeroize::Zeroizing;
25
26const TCP_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
27
28#[derive(Clone, PartialEq, Eq)]
33pub enum SshAuth {
34 Password(Zeroizing<String>),
36 Agent,
38 KeyFile {
40 path: PathBuf,
42 passphrase: Option<Zeroizing<String>>,
44 },
45}
46
47impl SshAuth {
48 pub fn password(password: impl Into<String>) -> Self {
50 Self::Password(Zeroizing::new(password.into()))
51 }
52
53 pub fn key_file(path: impl Into<PathBuf>, passphrase: Option<String>) -> Self {
55 Self::KeyFile {
56 path: path.into(),
57 passphrase: passphrase.map(Zeroizing::new),
58 }
59 }
60}
61
62impl fmt::Debug for SshAuth {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 match self {
65 Self::Password(_) => f.write_str("Password(..)"),
66 Self::Agent => f.write_str("Agent"),
67 Self::KeyFile { path, passphrase } => f
68 .debug_struct("KeyFile")
69 .field("path", path)
70 .field("passphrase", &passphrase.as_ref().map(|_| ".."))
71 .finish(),
72 }
73 }
74}
75
76#[derive(Clone, Debug, PartialEq, Eq)]
82#[non_exhaustive]
83pub enum HostKeyPolicy {
84 RejectAll,
86 Fingerprint(String),
92 KnownHosts(PathBuf),
96 AcceptNew(PathBuf),
99 AcceptAll,
101}
102
103#[derive(Clone, Debug, Default, PartialEq, Eq)]
105pub struct SshSessionOpts {
106 compression: Option<bool>,
107 keepalive: Option<Duration>,
108 kex: Option<String>,
109 host_key_algs: Option<String>,
110 ciphers: Option<String>,
111 macs: Option<String>,
112}
113
114impl SshSessionOpts {
115 pub fn new() -> Self {
117 Self::default()
118 }
119
120 pub fn compression(mut self, enabled: bool) -> Self {
122 self.compression = Some(enabled);
123 self
124 }
125
126 pub fn keepalive(mut self, interval: Duration) -> Self {
128 self.keepalive = Some(interval);
129 self
130 }
131
132 pub fn kex_algorithms(mut self, prefs: impl Into<String>) -> Self {
134 self.kex = Some(prefs.into());
135 self
136 }
137
138 pub fn host_key_algorithms(mut self, prefs: impl Into<String>) -> Self {
140 self.host_key_algs = Some(prefs.into());
141 self
142 }
143
144 pub fn ciphers(mut self, prefs: impl Into<String>) -> Self {
146 self.ciphers = Some(prefs.into());
147 self
148 }
149
150 pub fn macs(mut self, prefs: impl Into<String>) -> Self {
152 self.macs = Some(prefs.into());
153 self
154 }
155
156 pub fn compression_enabled(&self) -> Option<bool> {
158 self.compression
159 }
160
161 pub fn keepalive_interval(&self) -> Option<Duration> {
163 self.keepalive
164 }
165
166 pub fn kex(&self) -> Option<&str> {
168 self.kex.as_deref()
169 }
170
171 pub fn host_key_algs(&self) -> Option<&str> {
173 self.host_key_algs.as_deref()
174 }
175
176 pub fn ciphers_pref(&self) -> Option<&str> {
178 self.ciphers.as_deref()
179 }
180
181 pub fn macs_pref(&self) -> Option<&str> {
183 self.macs.as_deref()
184 }
185}
186
187#[derive(Clone, Debug, PartialEq, Eq)]
190pub struct SshJump {
191 host: String,
192 port: u16,
193 username: String,
194 auth: SshAuth,
195 host_key: HostKeyPolicy,
196 session: SshSessionOpts,
197}
198
199impl SshJump {
200 pub fn new(
202 host: impl Into<String>,
203 port: u16,
204 username: impl Into<String>,
205 auth: SshAuth,
206 ) -> Self {
207 SshJump {
208 host: host.into(),
209 port,
210 username: username.into(),
211 auth,
212 host_key: HostKeyPolicy::RejectAll,
213 session: SshSessionOpts::new(),
214 }
215 }
216
217 pub fn host_key(mut self, policy: HostKeyPolicy) -> Self {
219 self.host_key = policy;
220 self
221 }
222
223 pub fn session(mut self, opts: SshSessionOpts) -> Self {
225 self.session = opts;
226 self
227 }
228
229 pub fn host(&self) -> &str {
231 &self.host
232 }
233
234 pub fn port(&self) -> u16 {
236 self.port
237 }
238
239 pub fn username(&self) -> &str {
241 &self.username
242 }
243
244 pub fn auth(&self) -> &SshAuth {
246 &self.auth
247 }
248
249 pub fn host_key_policy(&self) -> &HostKeyPolicy {
251 &self.host_key
252 }
253
254 pub fn session_opts(&self) -> &SshSessionOpts {
256 &self.session
257 }
258}
259
260#[derive(Clone, Debug, PartialEq, Eq)]
264pub struct SshConfig {
265 host: String,
266 port: u16,
267 username: String,
268 auth: SshAuth,
269 host_key: HostKeyPolicy,
270 jumps: Vec<SshJump>,
271 session: SshSessionOpts,
272}
273
274impl SshConfig {
275 pub fn new(
278 host: impl Into<String>,
279 port: u16,
280 username: impl Into<String>,
281 auth: SshAuth,
282 ) -> Self {
283 SshConfig {
284 host: host.into(),
285 port,
286 username: username.into(),
287 auth,
288 host_key: HostKeyPolicy::RejectAll,
289 jumps: Vec::new(),
290 session: SshSessionOpts::new(),
291 }
292 }
293
294 pub fn host_key(mut self, policy: HostKeyPolicy) -> Self {
296 self.host_key = policy;
297 self
298 }
299
300 pub fn jump(mut self, jump: SshJump) -> Self {
302 self.jumps.push(jump);
303 self
304 }
305
306 pub fn session(mut self, opts: SshSessionOpts) -> Self {
308 self.session = opts;
309 self
310 }
311
312 pub fn host(&self) -> &str {
314 &self.host
315 }
316
317 pub fn port(&self) -> u16 {
319 self.port
320 }
321
322 pub fn username(&self) -> &str {
324 &self.username
325 }
326
327 pub fn auth(&self) -> &SshAuth {
329 &self.auth
330 }
331
332 pub fn host_key_policy(&self) -> &HostKeyPolicy {
334 &self.host_key
335 }
336
337 pub fn jumps(&self) -> &[SshJump] {
339 &self.jumps
340 }
341
342 pub fn session_opts(&self) -> &SshSessionOpts {
344 &self.session
345 }
346}
347
348#[derive(Clone)]
355pub struct JumpSession {
356 last: Arc<tokio::sync::Mutex<Handle<ClientHandler>>>,
357 _upstream: Vec<Arc<tokio::sync::Mutex<Handle<ClientHandler>>>>,
358 hops: Vec<(String, u16)>,
359}
360
361impl fmt::Debug for JumpSession {
362 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
363 f.debug_struct("JumpSession")
364 .field("hops", &self.hops)
365 .finish()
366 }
367}
368
369impl fmt::Display for JumpSession {
370 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371 f.write_str(&format_hops(
372 self.hops.iter().map(|(host, port)| (host.as_str(), *port)),
373 ))
374 }
375}
376
377impl JumpSession {
378 pub async fn connect(jumps: &[SshJump]) -> NetconfClientResult<Self> {
380 let mut hops = jumps.iter();
381 let first = hops.next().ok_or_else(|| {
382 NetconfClientError::new("JumpSession::connect requires at least one hop")
383 })?;
384 debug!("connecting via ProxyJump {}:{}", first.host, first.port);
385 let mut last = handshake_and_auth(
386 connect_tcp(&first.host, first.port).await?,
387 target_from_jump(first),
388 )
389 .await?;
390 let mut upstream = Vec::new();
391 for next in hops {
392 debug!("proxyjump next hop {}:{}", next.host, next.port);
393 let stream = open_jump(&last, &next.host, next.port).await?;
394 upstream.push(Arc::new(tokio::sync::Mutex::new(last)));
395 last = handshake_and_auth(stream, target_from_jump(next)).await?;
396 }
397 Ok(Self {
398 last: Arc::new(tokio::sync::Mutex::new(last)),
399 _upstream: upstream,
400 hops: jumps
401 .iter()
402 .map(|jump| (jump.host.clone(), jump.port))
403 .collect(),
404 })
405 }
406
407 pub async fn connect_device(&self, config: SshConfig) -> NetconfClientResult<SshTransport> {
411 let stream = {
412 let handle = self.last.lock().await;
413 if handle.is_closed() {
414 return Err(NetconfClientError::new(format!(
415 "jump session {self} is closed"
416 )));
417 }
418 open_jump(&handle, &config.host, config.port).await?
419 };
420 let session = handshake_and_auth(stream, target_from_config(&config)).await?;
421 let mut transport = open_netconf(session).await?;
422 transport._jumps = Some(self.clone());
423 Ok(transport)
424 }
425
426 pub fn is_closed(&self) -> bool {
428 self.last
429 .try_lock()
430 .map(|handle| handle.is_closed())
431 .unwrap_or(false)
432 }
433}
434
435pub struct JumpPool {
440 hops: Vec<SshJump>,
441 session: tokio::sync::Mutex<Option<JumpSession>>,
442}
443
444impl fmt::Debug for JumpPool {
445 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
446 f.debug_struct("JumpPool")
447 .field("hops", &format_jump_hops(&self.hops))
448 .finish()
449 }
450}
451
452impl JumpPool {
453 pub fn new(jumps: impl Into<Vec<SshJump>>) -> NetconfClientResult<Self> {
455 let hops = jumps.into();
456 if hops.is_empty() {
457 return Err(NetconfClientError::new(
458 "JumpPool::new requires at least one hop",
459 ));
460 }
461 Ok(Self {
462 hops,
463 session: tokio::sync::Mutex::new(None),
464 })
465 }
466
467 pub fn jumps(&self) -> &[SshJump] {
469 &self.hops
470 }
471
472 pub async fn connect_device(&self, config: SshConfig) -> NetconfClientResult<SshTransport> {
476 self.session().await?.connect_device(config).await
477 }
478
479 async fn session(&self) -> NetconfClientResult<JumpSession> {
480 let mut slot = self.session.lock().await;
481 if let Some(session) = slot.as_ref()
482 && !session.is_closed()
483 {
484 return Ok(session.clone());
485 }
486 let session = JumpSession::connect(&self.hops).await?;
488 *slot = Some(session.clone());
489 Ok(session)
490 }
491}
492
493pub struct SshTransport {
497 session: Handle<ClientHandler>,
498 framer: AsyncFramer<ChannelStream<client::Msg>>,
499 _jumps: Option<JumpSession>,
501}
502
503impl fmt::Debug for SshTransport {
504 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
505 f.debug_struct("SshTransport").finish_non_exhaustive()
506 }
507}
508
509impl SshTransport {
510 pub async fn connect(config: SshConfig) -> NetconfClientResult<SshTransport> {
516 if config.jumps.is_empty() {
517 let stream = connect_tcp(&config.host, config.port).await?;
518 let session = handshake_and_auth(stream, target_from_config(&config)).await?;
519 return open_netconf(session).await;
520 }
521 JumpSession::connect(&config.jumps)
522 .await?
523 .connect_device(config)
524 .await
525 }
526}
527
528#[async_trait]
529impl Transport for SshTransport {
530 async fn receive(&mut self) -> NetconfClientResult<String> {
531 self.framer.read_async().await
532 }
533
534 async fn write(&mut self, rpc: &str) -> NetconfClientResult<()> {
535 self.framer.write_async(rpc).await
536 }
537 async fn write_and_receive(&mut self, rpc: &str) -> NetconfClientResult<String> {
538 self.framer.write_async(rpc).await?;
539 self.framer.read_async().await
540 }
541
542 async fn close(&mut self) -> NetconfClientResult<()> {
543 if let Err(err) = self.framer.channel_mut().shutdown().await {
544 debug!("ssh channel shutdown: {err}");
545 }
546 self.session
547 .disconnect(Disconnect::ByApplication, "Shutdown", "")
548 .await
549 .map_err(map_russh)?;
550 self._jumps = None;
551 Ok(())
552 }
553
554 async fn upgrade(&mut self) {
555 self.framer.upgrade().await;
556 }
557}
558
559struct Target<'a> {
560 host: &'a str,
561 port: u16,
562 username: &'a str,
563 auth: &'a SshAuth,
564 host_key: &'a HostKeyPolicy,
565 session: &'a SshSessionOpts,
566}
567
568fn target_from_config(config: &SshConfig) -> Target<'_> {
569 Target {
570 host: &config.host,
571 port: config.port,
572 username: &config.username,
573 auth: &config.auth,
574 host_key: &config.host_key,
575 session: &config.session,
576 }
577}
578
579fn target_from_jump(jump: &SshJump) -> Target<'_> {
580 Target {
581 host: &jump.host,
582 port: jump.port,
583 username: &jump.username,
584 auth: &jump.auth,
585 host_key: &jump.host_key,
586 session: &jump.session,
587 }
588}
589
590struct ClientHandler {
591 host: String,
592 port: u16,
593 policy: HostKeyPolicy,
594}
595
596#[derive(Debug)]
597enum SshConnectError {
598 Client(NetconfClientError),
599 Protocol(russh::Error),
600}
601
602impl From<russh::Error> for SshConnectError {
603 fn from(err: russh::Error) -> Self {
604 Self::Protocol(err)
605 }
606}
607
608impl From<NetconfClientError> for SshConnectError {
609 fn from(err: NetconfClientError) -> Self {
610 Self::Client(err)
611 }
612}
613
614impl client::Handler for ClientHandler {
615 type Error = SshConnectError;
616
617 async fn check_server_key(
618 &mut self,
619 server_public_key: &PublicKeyOrCertificate,
620 ) -> Result<bool, Self::Error> {
621 verify_host_key(
622 &self.host,
623 self.port,
624 &self.policy,
625 &server_public_key.public_key(),
626 )?;
627 Ok(true)
628 }
629}
630
631async fn connect_tcp(host: &str, port: u16) -> NetconfClientResult<TcpStream> {
632 timeout(TCP_CONNECT_TIMEOUT, TcpStream::connect((host, port)))
633 .await
634 .map_err(|_| NetconfClientError::new(format!("timeout connecting to {host}:{port}")))?
635 .map_err(Into::into)
636}
637
638async fn open_jump(
639 jump_session: &Handle<ClientHandler>,
640 host: &str,
641 port: u16,
642) -> NetconfClientResult<ChannelStream<client::Msg>> {
643 let channel = jump_session
644 .channel_open_direct_tcpip(host, u32::from(port), "127.0.0.1", 22)
645 .await
646 .map_err(map_russh)?;
647 Ok(channel.into_stream())
648}
649
650async fn handshake_and_auth<R>(
651 stream: R,
652 target: Target<'_>,
653) -> NetconfClientResult<Handle<ClientHandler>>
654where
655 R: AsyncRead + AsyncWrite + Unpin + Send + 'static,
656{
657 let ssh_config = build_client_config(target.session)?;
658 let handler = ClientHandler {
659 host: target.host.to_string(),
660 port: target.port,
661 policy: target.host_key.clone(),
662 };
663 let mut session = client::connect_stream(Arc::new(ssh_config), stream, handler)
664 .await
665 .map_err(map_connect)?;
666 authenticate(
667 &mut session,
668 target.host,
669 target.port,
670 target.username,
671 target.auth,
672 )
673 .await?;
674 Ok(session)
675}
676
677async fn open_netconf(session: Handle<ClientHandler>) -> NetconfClientResult<SshTransport> {
678 let mut channel = session.channel_open_session().await.map_err(map_russh)?;
679 channel
680 .request_subsystem(true, "netconf")
681 .await
682 .map_err(map_russh)?;
683 let prefix = wait_netconf_subsystem(&mut channel).await?;
686 let mut framer = AsyncFramer::new(channel.into_stream());
687 if !prefix.is_empty() {
688 debug!(
689 "netconf subsystem sent {} bytes before Success",
690 prefix.len()
691 );
692 framer.push_incoming(&prefix);
693 }
694 Ok(SshTransport {
695 session,
696 framer,
697 _jumps: None,
698 })
699}
700
701async fn wait_netconf_subsystem(
702 channel: &mut Channel<client::Msg>,
703) -> NetconfClientResult<Vec<u8>> {
704 let mut prefix = Vec::new();
705 loop {
706 match channel.wait().await {
707 Some(ChannelMsg::Success) => {
708 debug!("netconf subsystem confirmed");
709 return Ok(prefix);
710 }
711 Some(ChannelMsg::Failure) => {
712 return Err(NetconfClientError::new(
713 "server refused the netconf subsystem",
714 ));
715 }
716 Some(ChannelMsg::Data { data }) => prefix.extend_from_slice(&data),
717 Some(ChannelMsg::ExtendedData { data, .. }) => prefix.extend_from_slice(&data),
718 Some(_) => {}
719 None => {
720 return Err(NetconfClientError::new(
721 "connection closed while requesting the netconf subsystem",
722 ));
723 }
724 }
725 }
726}
727
728fn build_client_config(opts: &SshSessionOpts) -> NetconfClientResult<client::Config> {
729 let mut preferred = Preferred::DEFAULT;
730 if let Some(enabled) = opts.compression {
731 preferred.compression = if enabled {
732 Cow::Owned(vec![
733 russh::compression::ZLIB,
734 russh::compression::ZLIB_LEGACY,
735 russh::compression::NONE,
736 ])
737 } else {
738 Cow::Owned(vec![russh::compression::NONE])
739 };
740 }
741 if let Some(kex) = opts.kex.as_deref() {
742 preferred.kex = Cow::Owned(parse_kex(kex)?);
743 }
744 if let Some(host_key) = opts.host_key_algs.as_deref() {
745 preferred.key = Cow::Owned(parse_host_keys(host_key)?);
746 }
747 if let Some(ciphers) = opts.ciphers.as_deref() {
748 preferred.cipher = Cow::Owned(parse_ciphers(ciphers)?);
749 }
750 if let Some(macs) = opts.macs.as_deref() {
751 preferred.mac = Cow::Owned(parse_macs(macs)?);
752 }
753 Ok(client::Config {
754 preferred,
755 keepalive_interval: opts.keepalive,
756 inactivity_timeout: None,
757 nodelay: true,
758 ..client::Config::default()
759 })
760}
761
762fn split_prefs(prefs: &str) -> impl Iterator<Item = &str> {
763 prefs
764 .split(',')
765 .map(str::trim)
766 .filter(|name| !name.is_empty())
767}
768
769fn parse_kex(prefs: &str) -> NetconfClientResult<Vec<russh::kex::Name>> {
770 let mut out = Vec::new();
771 for name in split_prefs(prefs) {
772 match russh::kex::Name::try_from(name) {
773 Ok(alg) => {
774 if !out.contains(&alg) {
775 out.push(alg);
776 }
777 }
778 Err(()) => warn!("Ignoring unknown SSH kex algorithm {name}"),
779 }
780 }
781 if out.is_empty() {
782 return Err(NetconfClientError::new(format!(
783 "no supported SSH kex algorithms in '{prefs}'"
784 )));
785 }
786 for ext in [
787 russh::kex::EXTENSION_SUPPORT_AS_CLIENT,
788 russh::kex::EXTENSION_OPENSSH_STRICT_KEX_AS_CLIENT,
789 ] {
790 if !out.contains(&ext) {
791 out.push(ext);
792 }
793 }
794 Ok(out)
795}
796
797fn parse_host_keys(prefs: &str) -> NetconfClientResult<Vec<keys::Algorithm>> {
798 let mut out = Vec::new();
799 for name in split_prefs(prefs) {
800 match keys::Algorithm::new(name) {
801 Ok(alg) => {
802 if !out.contains(&alg) {
803 out.push(alg);
804 }
805 }
806 Err(err) => warn!("Ignoring unknown SSH host-key algorithm {name}: {err}"),
807 }
808 }
809 if out.is_empty() {
810 return Err(NetconfClientError::new(format!(
811 "no supported SSH host-key algorithms in '{prefs}'"
812 )));
813 }
814 Ok(out)
815}
816
817fn parse_ciphers(prefs: &str) -> NetconfClientResult<Vec<russh::cipher::Name>> {
818 let mut out = Vec::new();
819 for name in split_prefs(prefs) {
820 match russh::cipher::Name::try_from(name) {
821 Ok(alg) => {
822 if !out.contains(&alg) {
823 out.push(alg);
824 }
825 }
826 Err(()) => warn!("Ignoring unknown SSH cipher {name}"),
827 }
828 }
829 if out.is_empty() {
830 return Err(NetconfClientError::new(format!(
831 "no supported SSH ciphers in '{prefs}'"
832 )));
833 }
834 Ok(out)
835}
836
837fn parse_macs(prefs: &str) -> NetconfClientResult<Vec<russh::mac::Name>> {
838 let mut out = Vec::new();
839 for name in split_prefs(prefs) {
840 match russh::mac::Name::try_from(name) {
841 Ok(alg) => {
842 if !out.contains(&alg) {
843 out.push(alg);
844 }
845 }
846 Err(()) => warn!("Ignoring unknown SSH MAC algorithm {name}"),
847 }
848 }
849 if out.is_empty() {
850 return Err(NetconfClientError::new(format!(
851 "no supported SSH MAC algorithms in '{prefs}'"
852 )));
853 }
854 Ok(out)
855}
856
857fn verify_host_key(
858 host: &str,
859 port: u16,
860 policy: &HostKeyPolicy,
861 key: &PublicKey,
862) -> NetconfClientResult<()> {
863 match policy {
864 HostKeyPolicy::KnownHosts(path) => {
865 return check_known_hosts(host, port, path, key, false);
866 }
867 HostKeyPolicy::AcceptNew(path) => {
868 return check_known_hosts(host, port, path, key, true);
869 }
870 _ => {}
871 }
872 let fingerprint = host_key_fingerprint(key);
873 if evaluate_host_key_policy(policy, &fingerprint) {
874 if matches!(policy, HostKeyPolicy::AcceptAll) {
875 warn!(
876 "Accepting SSH host key for {host} without verification ({fingerprint}) — \
877 set HostKeyPolicy::Fingerprint or HostKeyPolicy::KnownHosts for production use"
878 );
879 }
880 return Ok(());
881 }
882 let reason = match policy {
883 HostKeyPolicy::RejectAll => "RejectAll policy; pin the fingerprint or a known_hosts file",
884 HostKeyPolicy::Fingerprint(_) => "fingerprint does not match",
885 HostKeyPolicy::KnownHosts(_) | HostKeyPolicy::AcceptNew(_) => {
886 unreachable!("file policies return earlier")
887 }
888 HostKeyPolicy::AcceptAll => unreachable!("AcceptAll accepts every key"),
889 };
890 Err(NetconfClientError::HostKeyRejected {
891 host: host.to_string(),
892 fingerprint,
893 reason: reason.to_string(),
894 })
895}
896
897fn check_known_hosts(
898 host: &str,
899 port: u16,
900 path: &Path,
901 key: &PublicKey,
902 accept_new: bool,
903) -> NetconfClientResult<()> {
904 let fingerprint = host_key_fingerprint(key);
905 if !path.exists() && !accept_new {
906 return Err(NetconfClientError::new(format!(
907 "failed to read known_hosts {}: file not found",
908 path.display()
909 )));
910 }
911 match known_hosts_action(
912 keys::check_known_hosts_path(host, port, key, path),
913 accept_new,
914 ) {
915 KnownHostsAction::Allow => Ok(()),
916 KnownHostsAction::Pin => pin_new_host(path, host, port, key, &fingerprint),
917 KnownHostsAction::Reject(reason) => Err(NetconfClientError::HostKeyRejected {
918 host: host.to_string(),
919 fingerprint,
920 reason: reason.to_string(),
921 }),
922 }
923}
924
925#[derive(Debug, PartialEq, Eq)]
926enum KnownHostsAction {
927 Allow,
928 Pin,
929 Reject(&'static str),
930}
931
932#[derive(Debug)]
933enum KnownHostsCheck {
934 Match,
935 NotFound,
936 Mismatch,
937 Failure,
938}
939
940fn known_hosts_action(result: Result<bool, keys::Error>, accept_new: bool) -> KnownHostsAction {
941 known_hosts_action_from(classify_known_hosts(result), accept_new)
942}
943
944fn classify_known_hosts(result: Result<bool, keys::Error>) -> KnownHostsCheck {
945 match result {
946 Ok(true) => KnownHostsCheck::Match,
947 Ok(false) => KnownHostsCheck::NotFound,
948 Err(keys::Error::KeyChanged { .. }) => KnownHostsCheck::Mismatch,
949 Err(_) => KnownHostsCheck::Failure,
950 }
951}
952
953fn known_hosts_action_from(check: KnownHostsCheck, accept_new: bool) -> KnownHostsAction {
954 match check {
955 KnownHostsCheck::Match => KnownHostsAction::Allow,
956 KnownHostsCheck::NotFound if accept_new => KnownHostsAction::Pin,
957 other => KnownHostsAction::Reject(known_hosts_reason(other)),
958 }
959}
960
961fn pin_new_host(
962 path: &Path,
963 host: &str,
964 port: u16,
965 key: &PublicKey,
966 fingerprint: &str,
967) -> NetconfClientResult<()> {
968 known_hosts::learn_known_hosts_path(host, port, key, path).map_err(|err| {
969 NetconfClientError::new(format!(
970 "failed to record host key for {host} in {}: {err}",
971 path.display()
972 ))
973 })?;
974 warn!(
975 "Accepted new SSH host key for {host} ({fingerprint}); stored in {}",
976 path.display()
977 );
978 Ok(())
979}
980
981#[cfg(test)]
982fn known_hosts_host_spec(host: &str, port: u16) -> String {
983 if port == 22 {
984 host.to_string()
985 } else {
986 format!("[{host}]:{port}")
987 }
988}
989
990fn known_hosts_reason(check: KnownHostsCheck) -> &'static str {
991 match check {
992 KnownHostsCheck::Match => "matched",
993 KnownHostsCheck::Mismatch => "key does not match known_hosts",
994 KnownHostsCheck::NotFound => "host not in known_hosts",
995 KnownHostsCheck::Failure => "known_hosts check failed",
996 }
997}
998
999fn host_key_fingerprint(key: &PublicKey) -> String {
1000 format!("{}", key.fingerprint(HashAlg::Sha256))
1001}
1002
1003fn evaluate_host_key_policy(policy: &HostKeyPolicy, actual_fingerprint: &str) -> bool {
1007 match policy {
1008 HostKeyPolicy::AcceptAll => true,
1009 HostKeyPolicy::RejectAll => false,
1010 HostKeyPolicy::Fingerprint(expected) => fingerprints_match(expected, actual_fingerprint),
1011 HostKeyPolicy::KnownHosts(_) | HostKeyPolicy::AcceptNew(_) => false,
1012 }
1013}
1014
1015fn fingerprints_match(expected: &str, actual: &str) -> bool {
1016 let expected = normalize_fingerprint(expected);
1017 let actual = normalize_fingerprint(actual);
1018 !expected.is_empty() && expected == actual
1019}
1020
1021fn normalize_fingerprint(value: &str) -> String {
1022 value
1023 .trim()
1024 .strip_prefix("SHA256:")
1025 .unwrap_or(value.trim())
1026 .trim_end_matches('=')
1027 .to_string()
1028}
1029
1030async fn authenticate(
1031 session: &mut Handle<ClientHandler>,
1032 host: &str,
1033 port: u16,
1034 username: &str,
1035 auth: &SshAuth,
1036) -> NetconfClientResult<()> {
1037 let success = match auth {
1038 SshAuth::Password(password) => session
1039 .authenticate_password(username, password.as_str())
1040 .await
1041 .map_err(map_russh)?
1042 .success(),
1043 SshAuth::Agent => authenticate_agent(session, username).await?,
1044 SshAuth::KeyFile { path, passphrase } => {
1045 authenticate_key_file(
1046 session,
1047 username,
1048 path,
1049 passphrase.as_ref().map(|secret| secret.as_str()),
1050 )
1051 .await?
1052 }
1053 };
1054 if success {
1055 Ok(())
1056 } else {
1057 Err(NetconfClientError::new(format!(
1058 "SSH authentication failed for {username}@{host}:{port}"
1059 )))
1060 }
1061}
1062
1063async fn authenticate_key_file(
1064 session: &mut Handle<ClientHandler>,
1065 username: &str,
1066 path: &Path,
1067 passphrase: Option<&str>,
1068) -> NetconfClientResult<bool> {
1069 let key = keys::load_secret_key(path, passphrase).map_err(map_keys)?;
1070 let hash = session
1071 .best_supported_rsa_hash()
1072 .await
1073 .map_err(map_russh)?
1074 .flatten();
1075 Ok(session
1076 .authenticate_publickey(username, PrivateKeyWithHashAlg::new(Arc::new(key), hash))
1077 .await
1078 .map_err(map_russh)?
1079 .success())
1080}
1081
1082async fn authenticate_agent(
1083 session: &mut Handle<ClientHandler>,
1084 username: &str,
1085) -> NetconfClientResult<bool> {
1086 let mut agent = connect_agent().await?;
1087 let identities = agent.request_identities().await.map_err(map_keys)?;
1088 if identities.is_empty() {
1089 return Ok(false);
1090 }
1091 let hash = session
1092 .best_supported_rsa_hash()
1093 .await
1094 .map_err(map_russh)?
1095 .flatten();
1096 for identity in identities {
1097 let result = match identity {
1098 AgentIdentity::PublicKey { key, comment } => {
1099 trace!("trying ssh-agent identity {comment}");
1100 session
1101 .authenticate_publickey_with(username, key, hash, &mut agent)
1102 .await
1103 }
1104 AgentIdentity::Certificate {
1105 certificate,
1106 comment,
1107 } => {
1108 trace!("trying ssh-agent certificate {comment}");
1109 session
1110 .authenticate_certificate_with(username, certificate, hash, &mut agent)
1111 .await
1112 }
1113 };
1114 match result {
1115 Ok(auth) if auth.success() => return Ok(true),
1116 Ok(_) => continue,
1117 Err(err) => {
1118 trace!("ssh-agent identity rejected: {err}");
1119 }
1120 }
1121 }
1122 Ok(false)
1123}
1124
1125type DynAgent = AgentClient<Box<dyn keys::agent::client::AgentStream + Send + Unpin>>;
1126
1127async fn connect_agent() -> NetconfClientResult<DynAgent> {
1128 #[cfg(unix)]
1129 {
1130 AgentClient::connect_env()
1131 .await
1132 .map(AgentClient::dynamic)
1133 .map_err(map_keys)
1134 }
1135 #[cfg(windows)]
1136 {
1137 if let Ok(sock) = std::env::var("SSH_AUTH_SOCK")
1138 && let Ok(client) = AgentClient::connect_named_pipe(&sock).await
1139 {
1140 return Ok(client.dynamic());
1141 }
1142 if let Ok(client) = AgentClient::connect_named_pipe(r"\\.\pipe\openssh-ssh-agent").await {
1143 return Ok(client.dynamic());
1144 }
1145 AgentClient::connect_pageant()
1146 .await
1147 .map(AgentClient::dynamic)
1148 .map_err(map_keys)
1149 }
1150 #[cfg(not(any(unix, windows)))]
1151 {
1152 Err(NetconfClientError::new(
1153 "ssh-agent is not supported on this platform",
1154 ))
1155 }
1156}
1157
1158fn format_hops<'a>(hops: impl Iterator<Item = (&'a str, u16)>) -> String {
1159 hops.map(|(host, port)| format!("{host}:{port}"))
1160 .collect::<Vec<_>>()
1161 .join(" -> ")
1162}
1163
1164fn format_jump_hops(jumps: &[SshJump]) -> String {
1165 format_hops(jumps.iter().map(|jump| (jump.host.as_str(), jump.port)))
1166}
1167
1168fn map_connect(err: SshConnectError) -> NetconfClientError {
1169 match err {
1170 SshConnectError::Client(err) => err,
1171 SshConnectError::Protocol(err) => map_russh(err),
1172 }
1173}
1174
1175fn map_russh(err: russh::Error) -> NetconfClientError {
1176 match err {
1177 russh::Error::IO(io) => NetconfClientError::Io(io),
1178 russh::Error::HUP | russh::Error::Disconnect | russh::Error::RecvError => {
1179 NetconfClientError::Io(std::io::Error::new(
1180 std::io::ErrorKind::UnexpectedEof,
1181 err.to_string(),
1182 ))
1183 }
1184 other => NetconfClientError::Ssh(other.to_string()),
1185 }
1186}
1187
1188fn map_keys(err: keys::Error) -> NetconfClientError {
1189 match err {
1190 keys::Error::IO(io) => NetconfClientError::Io(io),
1191 other => NetconfClientError::Ssh(other.to_string()),
1192 }
1193}
1194
1195#[cfg(test)]
1196mod tests {
1197 use super::*;
1198
1199 #[test]
1200 fn ssh_config_defaults_to_reject_all_and_no_jump() {
1201 let cfg = SshConfig::new("192.0.2.10", 830, "netconf", SshAuth::password("x"));
1202 assert_eq!(cfg.host(), "192.0.2.10");
1203 assert_eq!(cfg.port(), 830);
1204 assert_eq!(cfg.username(), "netconf");
1205 assert_eq!(cfg.host_key_policy(), &HostKeyPolicy::RejectAll);
1206 assert!(cfg.jumps().is_empty());
1207 assert!(matches!(cfg.auth(), SshAuth::Password(_)));
1208 }
1209
1210 #[test]
1211 fn ssh_config_builder_sets_fingerprint_and_jump() {
1212 let jump = SshJump::new("jump", 22, "jump-user", SshAuth::Agent)
1213 .host_key(HostKeyPolicy::AcceptAll)
1214 .session(SshSessionOpts::new().compression(true));
1215 let cfg = SshConfig::new("192.0.2.10", 830, "netconf", SshAuth::Agent)
1216 .host_key(HostKeyPolicy::Fingerprint("SHA256:abc".into()))
1217 .session(
1218 SshSessionOpts::new()
1219 .kex_algorithms("curve25519-sha256")
1220 .keepalive(Duration::from_secs(15)),
1221 )
1222 .jump(jump.clone());
1223 assert_eq!(
1224 cfg.host_key_policy(),
1225 &HostKeyPolicy::Fingerprint("SHA256:abc".into())
1226 );
1227 assert_eq!(cfg.session_opts().kex(), Some("curve25519-sha256"));
1228 assert_eq!(
1229 cfg.session_opts().keepalive_interval(),
1230 Some(Duration::from_secs(15))
1231 );
1232 let hop = &cfg.jumps()[0];
1233 assert_eq!(hop.host(), "jump");
1234 assert_eq!(hop.port(), 22);
1235 assert_eq!(hop.username(), "jump-user");
1236 assert_eq!(hop.auth(), &SshAuth::Agent);
1237 assert_eq!(hop.host_key_policy(), &HostKeyPolicy::AcceptAll);
1238 assert_eq!(hop.session_opts().compression_enabled(), Some(true));
1239 }
1240
1241 #[test]
1242 fn ssh_config_jump_appends_hops_in_order() {
1243 let cfg = SshConfig::new("192.0.2.10", 830, "netconf", SshAuth::Agent)
1244 .jump(SshJump::new("jump1", 22, "u1", SshAuth::Agent))
1245 .jump(SshJump::new("jump2", 2222, "u2", SshAuth::Agent));
1246 let hops = cfg.jumps();
1247 assert_eq!(hops.len(), 2);
1248 assert_eq!(hops[0].host(), "jump1");
1249 assert_eq!(hops[0].port(), 22);
1250 assert_eq!(hops[1].host(), "jump2");
1251 assert_eq!(hops[1].port(), 2222);
1252 }
1253
1254 #[test]
1255 fn known_hosts_reason_maps_check_results() {
1256 assert_eq!(
1257 known_hosts_reason(KnownHostsCheck::Mismatch),
1258 "key does not match known_hosts"
1259 );
1260 assert_eq!(
1261 known_hosts_reason(KnownHostsCheck::NotFound),
1262 "host not in known_hosts"
1263 );
1264 assert_eq!(
1265 known_hosts_reason(KnownHostsCheck::Failure),
1266 "known_hosts check failed"
1267 );
1268 }
1269
1270 #[test]
1271 fn accept_new_pins_unknown_and_rejects_mismatch() {
1272 assert_eq!(
1273 known_hosts_action_from(KnownHostsCheck::NotFound, true),
1274 KnownHostsAction::Pin
1275 );
1276 assert_eq!(
1277 known_hosts_action_from(KnownHostsCheck::Mismatch, true),
1278 KnownHostsAction::Reject("key does not match known_hosts")
1279 );
1280 assert_eq!(
1281 known_hosts_action_from(KnownHostsCheck::NotFound, false),
1282 KnownHostsAction::Reject("host not in known_hosts")
1283 );
1284 assert_eq!(
1285 known_hosts_action_from(KnownHostsCheck::Match, true),
1286 KnownHostsAction::Allow
1287 );
1288 }
1289
1290 #[test]
1291 fn classify_known_hosts_maps_russh_results() {
1292 assert!(matches!(
1293 classify_known_hosts(Ok(true)),
1294 KnownHostsCheck::Match
1295 ));
1296 assert!(matches!(
1297 classify_known_hosts(Ok(false)),
1298 KnownHostsCheck::NotFound
1299 ));
1300 assert!(matches!(
1301 classify_known_hosts(Err(keys::Error::KeyChanged { line: 3 })),
1302 KnownHostsCheck::Mismatch
1303 ));
1304 assert!(matches!(
1305 classify_known_hosts(Err(keys::Error::CouldNotReadKey)),
1306 KnownHostsCheck::Failure
1307 ));
1308 }
1309
1310 #[test]
1311 fn known_hosts_host_spec_uses_brackets_when_not_port_22() {
1312 assert_eq!(known_hosts_host_spec("router", 22), "router");
1313 assert_eq!(known_hosts_host_spec("router", 830), "[router]:830");
1314 assert_eq!(
1315 known_hosts_host_spec("2001:db8::1", 830),
1316 "[2001:db8::1]:830"
1317 );
1318 }
1319
1320 #[test]
1321 fn ssh_err_wraps_without_leaking_the_crate_type() {
1322 let io = map_russh(russh::Error::IO(std::io::Error::new(
1323 std::io::ErrorKind::UnexpectedEof,
1324 "pipe closed",
1325 )));
1326 assert!(
1327 matches!(&io, NetconfClientError::Io(err) if err.kind() == std::io::ErrorKind::UnexpectedEof),
1328 "{io:?}"
1329 );
1330 let eof = map_russh(russh::Error::HUP);
1331 assert!(
1332 matches!(&eof, NetconfClientError::Io(err) if err.kind() == std::io::ErrorKind::UnexpectedEof),
1333 "{eof:?}"
1334 );
1335 let other = map_russh(russh::Error::NotAuthenticated);
1336 assert!(
1337 matches!(&other, NetconfClientError::Ssh(msg) if msg.to_ascii_lowercase().contains("authenticated")),
1338 "{other:?}"
1339 );
1340 }
1341
1342 #[test]
1343 fn reject_all_rejects_and_accept_all_accepts() {
1344 assert!(!evaluate_host_key_policy(
1345 &HostKeyPolicy::RejectAll,
1346 "SHA256:abc"
1347 ));
1348 assert!(evaluate_host_key_policy(
1349 &HostKeyPolicy::AcceptAll,
1350 "SHA256:abc"
1351 ));
1352 }
1353
1354 #[test]
1355 fn fingerprint_match_is_tolerant_of_prefix_and_padding() {
1356 let actual = "SHA256:47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU";
1357 assert!(evaluate_host_key_policy(
1358 &HostKeyPolicy::Fingerprint(actual.into()),
1359 actual
1360 ));
1361 assert!(evaluate_host_key_policy(
1362 &HostKeyPolicy::Fingerprint("47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU".into()),
1363 actual
1364 ));
1365 assert!(evaluate_host_key_policy(
1366 &HostKeyPolicy::Fingerprint(
1367 "SHA256:47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=".into()
1368 ),
1369 actual
1370 ));
1371 assert!(!evaluate_host_key_policy(
1372 &HostKeyPolicy::Fingerprint("SHA256:nope".into()),
1373 actual
1374 ));
1375 assert!(!evaluate_host_key_policy(
1376 &HostKeyPolicy::Fingerprint(String::new()),
1377 actual
1378 ));
1379 }
1380
1381 #[test]
1382 fn ssh_auth_debug_redacts_secrets() {
1383 let password = format!("{:?}", SshAuth::password("secret"));
1384 assert!(!password.contains("secret"), "{password}");
1385 let key = format!("{:?}", SshAuth::key_file("/tmp/id", Some("s3cret".into())));
1386 assert!(!key.contains("s3cret"), "{key}");
1387 assert!(key.contains("/tmp/id"), "{key}");
1388 }
1389
1390 #[test]
1391 fn parse_kex_keeps_known_and_appends_extensions() {
1392 let parsed = parse_kex("curve25519-sha256,not-a-real-kex").unwrap();
1393 assert!(parsed.contains(&russh::kex::CURVE25519));
1394 assert!(parsed.contains(&russh::kex::EXTENSION_SUPPORT_AS_CLIENT));
1395 assert!(parsed.contains(&russh::kex::EXTENSION_OPENSSH_STRICT_KEX_AS_CLIENT));
1396 assert_eq!(parsed[0], russh::kex::CURVE25519);
1397 }
1398
1399 #[test]
1400 fn parse_kex_rejects_empty_or_unknown_only() {
1401 assert!(parse_kex("").is_err());
1402 assert!(parse_kex("not-a-real-kex").is_err());
1403 }
1404
1405 #[test]
1406 fn parse_ciphers_and_macs_keep_known() {
1407 let ciphers = parse_ciphers("aes256-ctr,chacha20-poly1305@openssh.com").unwrap();
1408 assert_eq!(ciphers[0], russh::cipher::AES_256_CTR);
1409 assert_eq!(ciphers[1], russh::cipher::CHACHA20_POLY1305);
1410 let macs = parse_macs("hmac-sha2-256,hmac-sha2-512").unwrap();
1411 assert_eq!(macs[0], russh::mac::HMAC_SHA256);
1412 assert_eq!(macs[1], russh::mac::HMAC_SHA512);
1413 }
1414
1415 #[test]
1416 fn parse_host_keys_keeps_known() {
1417 let keys = parse_host_keys("ssh-ed25519,rsa-sha2-256").unwrap();
1418 assert_eq!(keys[0], russh::keys::Algorithm::Ed25519);
1419 assert_eq!(
1420 keys[1],
1421 russh::keys::Algorithm::Rsa {
1422 hash: Some(HashAlg::Sha256)
1423 }
1424 );
1425 }
1426
1427 #[test]
1428 fn build_client_config_maps_compression_and_keepalive() {
1429 let opts = SshSessionOpts::new()
1430 .compression(true)
1431 .keepalive(Duration::from_secs(15))
1432 .ciphers("aes256-ctr");
1433 let cfg = build_client_config(&opts).unwrap();
1434 assert_eq!(cfg.keepalive_interval, Some(Duration::from_secs(15)));
1435 assert_eq!(cfg.preferred.cipher[0], russh::cipher::AES_256_CTR);
1436 assert_eq!(cfg.preferred.compression[0], russh::compression::ZLIB);
1437 }
1438
1439 #[test]
1440 fn jump_pool_requires_a_hop() {
1441 let err = JumpPool::new(Vec::<SshJump>::new()).unwrap_err();
1442 assert!(err.to_string().contains("at least one hop"), "{err}");
1443 }
1444
1445 #[tokio::test]
1446 async fn jump_session_requires_a_hop() {
1447 let err = JumpSession::connect(&[]).await.unwrap_err();
1448 assert!(err.to_string().contains("at least one hop"), "{err}");
1449 }
1450
1451 #[test]
1452 fn format_jump_hops_joins_chain() {
1453 let hops = [
1454 SshJump::new("jump1", 22, "u1", SshAuth::Agent),
1455 SshJump::new("jump2", 2222, "u2", SshAuth::Agent),
1456 ];
1457 assert_eq!(format_jump_hops(&hops), "jump1:22 -> jump2:2222");
1458 }
1459}