Debian Codegraph @

_transport_rs/src/ssh/russh_vendor.rs

raw
1 //! russh-backed SSH vendor.
2 //!
3 //! Replaces `dromedary/ssh/paramiko.py`. Gated behind the `russh` Cargo
4 //! feature (on by default).
5 //!
6 //! Progress through the migration sub-steps:
7 //! * 5a ✓ — TCP, password auth, trust-on-first-use host-key acceptance,
8 //! SFTP subsystem + `exec` command channel.
9 //! * 5b ✓ — SSH agent authentication via `$SSH_AUTH_SOCK`.
10 //! * 5c ✓ — `~/.ssh/id_rsa` / `id_dsa` key-file auth with passphrase prompt.
11 //! * 5d ✓ — `known_hosts` load/save and host-key mismatch rejection.
12 //! * 5e ✓ — `auth_none` probe + `_config.get_auth_password` fallback +
13 //! keyboard-interactive with the password as sole response.
14
15 use crate::sftp::{BoxedChannel, SFTPClient};
16 use pyo3::exceptions::PyRuntimeError;
17 use pyo3::import_exception;
18 use pyo3::prelude::*;
19 use pyo3::types::PyDict;
20 use std::io::{Read, Write};
21 use std::path::{Path, PathBuf};
22 use std::sync::{Arc, Mutex};
23 use std::time::Duration;
24 use tokio::io::{AsyncReadExt, AsyncWriteExt};
25 use tokio::runtime::Runtime;
26
27 import_exception!(dromedary.errors, SocketConnectionError);
28 import_exception!(dromedary.errors, TransportError);
29
30 // ---------------------------------------------------------------------------
31 // Host-key verification handler
32 // ---------------------------------------------------------------------------
33
34 /// Records *why* `check_server_key` returned `Ok(false)` so the caller can
35 /// raise the right Python exception after russh collapses the rejection
36 /// into `Error::UnknownKey`.
37 #[derive(Default)]
38 struct HostKeyVerdict {
39 mismatch: Option<HostKeyMismatch>,
40 }
41
42 struct HostKeyMismatch {
43 host: String,
44 expected_fp: String,
45 actual_fp: String,
46 system_path: PathBuf,
47 dromedary_path: PathBuf,
48 }
49
50 /// Client-side handler that verifies the remote server key against the
51 /// user's `~/.ssh/known_hosts` **and** dromedary's `<config_dir>/
52 /// ssh_host_keys`, trust-on-first-use into the dromedary file. Mirrors
53 /// `ParamikoVendor._connect` at paramiko.py:240 so both stores stay in
54 /// sync between the two backends during the migration.
55 struct VerifyingHandler {
56 host: String,
57 port: u16,
58 system_path: PathBuf,
59 dromedary_path: PathBuf,
60 verdict: Arc<Mutex<HostKeyVerdict>>,
61 }
62
63 impl russh::client::Handler for VerifyingHandler {
64 type Error = russh::Error;
65
66 async fn check_server_key(
67 &mut self,
68 server_public_key: &russh::keys::ssh_key::PublicKey,
69 ) -> Result<bool, Self::Error> {
70 match check_host_key(
71 &self.host,
72 self.port,
73 server_public_key,
74 &self.system_path,
75 &self.dromedary_path,
76 ) {
77 HostKeyCheck::Match => Ok(true),
78 HostKeyCheck::Unknown => {
79 // Trust-on-first-use: store into dromedary's file only
80 // (same as paramiko's `BRZ_HOSTKEYS.add` + `save_host_keys`).
81 log::warn!(
82 "Adding {} host key for {}: {}",
83 server_public_key.algorithm(),
84 self.host,
85 server_public_key.fingerprint(Default::default())
86 );
87 if let Err(e) = russh::keys::known_hosts::learn_known_hosts_path(
88 &self.host,
89 self.port,
90 server_public_key,
91 &self.dromedary_path,
92 ) {
93 log::debug!(
94 "failed to save host key to {}: {}",
95 self.dromedary_path.display(),
96 e
97 );
98 }
99 Ok(true)
100 }
101 HostKeyCheck::Mismatch { expected_fp } => {
102 self.verdict.lock().unwrap().mismatch = Some(HostKeyMismatch {
103 host: self.host.clone(),
104 expected_fp,
105 actual_fp: server_public_key
106 .fingerprint(Default::default())
107 .to_string(),
108 system_path: self.system_path.clone(),
109 dromedary_path: self.dromedary_path.clone(),
110 });
111 Ok(false)
112 }
113 }
114 }
115 }
116
117 enum HostKeyCheck {
118 Match,
119 Unknown,
120 Mismatch { expected_fp: String },
121 }
122
123 /// Check both the system file and dromedary's file. A mismatch in either
124 /// file is fatal (it shadows a prior trusted entry). An entry only in the
125 /// system file is acceptable without writing to the dromedary file.
126 fn check_host_key(
127 host: &str,
128 port: u16,
129 key: &russh::keys::ssh_key::PublicKey,
130 system_path: &Path,
131 dromedary_path: &Path,
132 ) -> HostKeyCheck {
133 for path in [system_path, dromedary_path] {
134 match russh::keys::check_known_hosts_path(host, port, key, path) {
135 Ok(true) => return HostKeyCheck::Match,
136 Ok(false) => continue,
137 Err(russh::keys::Error::KeyChanged { line }) => {
138 // Surface the recorded key so we can include its fingerprint
139 // in the error message.
140 let expected_fp = lookup_recorded_fingerprint(host, port, path, line);
141 return HostKeyCheck::Mismatch { expected_fp };
142 }
143 Err(e) => {
144 log::debug!("reading {}: {}", path.display(), e);
145 }
146 }
147 }
148 HostKeyCheck::Unknown
149 }
150
151 /// Pull the fingerprint of the *recorded* key on a specific line so a
152 /// mismatch error can show "expected X, got Y". Returns `<unknown>` if the
153 /// file can't be reread — the caller still raises `TransportError`.
154 fn lookup_recorded_fingerprint(host: &str, port: u16, path: &Path, line: usize) -> String {
155 match russh::keys::known_hosts::known_host_keys_path(host, port, path) {
156 Ok(entries) => entries
157 .into_iter()
158 .find(|(l, _)| *l == line)
159 .map(|(_, k)| k.fingerprint(Default::default()).to_string())
160 .unwrap_or_else(|| "<unknown>".to_string()),
161 Err(_) => "<unknown>".to_string(),
162 }
163 }
164
165 // ---------------------------------------------------------------------------
166 // Blocking bridge: async russh ChannelStream -> sync Read + Write
167 // ---------------------------------------------------------------------------
168
169 /// Wraps an async `ChannelStream` so it can be driven by synchronous SFTP
170 /// code. Each `read` / `write` call `block_on`s the owned runtime.
171 ///
172 /// The `Runtime` is held in an `Arc` so the same runtime that performed the
173 /// SSH handshake also services subsequent channel I/O — otherwise the inner
174 /// tokio tasks spawned by russh would be orphaned.
175 struct BlockingChannel {
176 runtime: Arc<Runtime>,
177 stream: russh::ChannelStream<russh::client::Msg>,
178 }
179
180 impl Read for BlockingChannel {
181 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
182 self.runtime.block_on(self.stream.read(buf))
183 }
184 }
185
186 impl Write for BlockingChannel {
187 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
188 self.runtime.block_on(self.stream.write(buf))
189 }
190
191 fn flush(&mut self) -> std::io::Result<()> {
192 self.runtime.block_on(self.stream.flush())
193 }
194 }
195
196 // ---------------------------------------------------------------------------
197 // Error mapping
198 // ---------------------------------------------------------------------------
199
200 fn connect_err(host: &str, port: Option<u16>, e: impl std::fmt::Display) -> PyErr {
201 SocketConnectionError::new_err((
202 host.to_string(),
203 port.map(|p| format!(":{p}")).unwrap_or_default(),
204 "Failed to connect to",
205 e.to_string(),
206 ))
207 }
208
209 // ---------------------------------------------------------------------------
210 // Connection wrapper for `exec`-style SSH sessions
211 // ---------------------------------------------------------------------------
212
213 /// Counterpart to `SSHSubprocessConnection` for the russh transport. Unlike
214 /// the subprocess variant it doesn't expose a raw fd — the remote command's
215 /// stdio is read/written through the same async runtime that performed the
216 /// handshake.
217 #[pyclass(module = "dromedary._transport_rs.ssh", name = "RusshSSHConnection")]
218 pub(crate) struct RusshSSHConnection {
219 inner: Mutex<Option<BlockingChannel>>,
220 }
221
222 #[pymethods]
223 impl RusshSSHConnection {
224 fn send(&self, py: Python, data: &[u8]) -> PyResult<usize> {
225 py.detach(|| {
226 let mut guard = self.inner.lock().unwrap();
227 let ch = guard
228 .as_mut()
229 .ok_or_else(|| PyRuntimeError::new_err("connection closed"))?;
230 ch.write(data)
231 .map_err(|e| PyRuntimeError::new_err(format!("send failed: {e}")))
232 })
233 }
234
235 fn recv(&self, py: Python, count: usize) -> PyResult<Vec<u8>> {
236 py.detach(|| {
237 let mut guard = self.inner.lock().unwrap();
238 let ch = guard
239 .as_mut()
240 .ok_or_else(|| PyRuntimeError::new_err("connection closed"))?;
241 let mut buf = vec![0u8; count];
242 let n = ch
243 .read(&mut buf)
244 .map_err(|e| PyRuntimeError::new_err(format!("recv failed: {e}")))?;
245 buf.truncate(n);
246 Ok(buf)
247 })
248 }
249
250 fn close(&self) -> PyResult<()> {
251 // Drops the underlying stream; russh will send channel_close when
252 // the Channel's write half is dropped.
253 let _ = self.inner.lock().unwrap().take();
254 Ok(())
255 }
256 }
257
258 // ---------------------------------------------------------------------------
259 // Vendor
260 // ---------------------------------------------------------------------------
261
262 #[pyclass(module = "dromedary._transport_rs.ssh", name = "RusshVendor")]
263 pub(crate) struct RusshVendor;
264
265 impl RusshVendor {
266 /// Shared connection path: TCP connect, SSH handshake, password auth,
267 /// return an open session handle plus the runtime that owns it.
268 ///
269 /// `key_files` is loaded (with a GIL-requiring passphrase prompt on
270 /// encrypted keys) *before* we enter async, so the passphrase prompt
271 /// never races the tokio runtime.
272 fn connect(
273 py: Python,
274 username: Option<&str>,
275 password: Option<&str>,
276 host: &str,
277 port: Option<u16>,
278 ) -> PyResult<(Arc<Runtime>, russh::client::Handle<VerifyingHandler>)> {
279 let user = username
280 .map(str::to_string)
281 .unwrap_or_else(|| resolve_username(py, host, port));
282
283 // Load key files while we still hold the GIL: decoding an
284 // encrypted key needs to call back into Python's `_ui.get_password`.
285 let key_files = load_default_keyfiles(py);
286
287 // Resolve host-key paths while holding the GIL too:
288 // `dromedary._bedding.config_dir` is an embedder-overridable
289 // function on the Python side.
290 let system_path = system_known_hosts_path();
291 let dromedary_path = dromedary_host_keys_path(py);
292
293 let port_nr = port.unwrap_or(22);
294 let host_owned = host.to_string();
295 let verdict = Arc::new(Mutex::new(HostKeyVerdict::default()));
296 let password = password.map(str::to_string);
297
298 // Phase 1: connect + agent/keys/probe/supplied-password. Runs with
299 // GIL released.
300 type Phase1 = (
301 Arc<Runtime>,
302 russh::client::Handle<VerifyingHandler>,
303 AuthPhaseOutcome,
304 );
305 let phase1: Result<Phase1, AuthError> = py.detach({
306 let verdict = verdict.clone();
307 let host_owned = host_owned.clone();
308 let user = user.clone();
309 move || {
310 let runtime = Arc::new(
311 tokio::runtime::Builder::new_current_thread()
312 .enable_all()
313 .build()
314 .map_err(|e| {
315 AuthError::Russh(russh::Error::IO(std::io::Error::other(format!(
316 "runtime build: {e}"
317 ))))
318 })?,
319 );
320
321 let addr = (host_owned.clone(), port_nr);
322 let config = Arc::new(russh::client::Config {
323 inactivity_timeout: Some(Duration::from_secs(3600)),
324 ..Default::default()
325 });
326 let handler = VerifyingHandler {
327 host: host_owned,
328 port: port_nr,
329 system_path,
330 dromedary_path,
331 verdict,
332 };
333
334 runtime
335 .block_on(async move {
336 let mut session = russh::client::connect(config, addr, handler)
337 .await
338 .map_err(AuthError::Russh)?;
339 let outcome = authenticate_pre_prompt(
340 &mut session,
341 &user,
342 password.as_deref(),
343 &key_files,
344 )
345 .await?;
346 Ok::<_, AuthError>((session, outcome))
347 })
348 .map(|(session, outcome)| (runtime, session, outcome))
349 }
350 });
351
352 let (runtime, handle, outcome) =
353 phase1.map_err(|e| connect_or_hostkey_err(&host_owned, Some(port_nr), &verdict, e))?;
354
355 if matches!(outcome, AuthPhaseOutcome::Authenticated) {
356 return Ok((runtime, handle));
357 }
358
359 // Phase 2 (GIL held): ask Python for a password. `None` means the
360 // user cancelled — paramiko.py:138 treats that as a hard failure.
361 let Some(prompt_pw) = prompt_auth_password(py, host, port, &user) else {
362 return Err(connect_or_hostkey_err(
363 &host_owned,
364 Some(port_nr),
365 &verdict,
366 AuthError::NoMethodsSucceeded,
367 ));
368 };
369
370 // Phase 3 (GIL released): try the prompted password. The handle
371 // moves into the closure and comes back out with the result so
372 // the caller can still use it.
373 let (handle, result) = py.detach({
374 let runtime = runtime.clone();
375 move || {
376 let mut handle = handle;
377 let r = runtime.block_on(try_password_phase(&mut handle, &user, &prompt_pw));
378 (handle, r)
379 }
380 });
381
382 match result {
383 Ok(()) => Ok((runtime, handle)),
384 Err(e) => Err(connect_or_hostkey_err(
385 &host_owned,
386 Some(port_nr),
387 &verdict,
388 e,
389 )),
390 }
391 }
392 }
393
394 /// Translate an `AuthError` into the right Python exception. `UnknownKey`
395 /// paired with a recorded mismatch becomes a `TransportError`; everything
396 /// else stays a `SocketConnectionError` (consistent with paramiko.py).
397 fn connect_or_hostkey_err(
398 host: &str,
399 port: Option<u16>,
400 verdict: &Mutex<HostKeyVerdict>,
401 e: AuthError,
402 ) -> PyErr {
403 if let AuthError::Russh(russh::Error::UnknownKey) = &e {
404 if let Some(m) = verdict.lock().unwrap().mismatch.take() {
405 return TransportError::new_err((
406 format!(
407 "Host keys for {} do not match! {} != {}",
408 m.host, m.expected_fp, m.actual_fp
409 ),
410 format!(
411 "Try editing {} or {}",
412 m.system_path.display(),
413 m.dromedary_path.display()
414 ),
415 ));
416 }
417 }
418 connect_err(host, port, e)
419 }
420
421 // ---------------------------------------------------------------------------
422 // Authentication
423 // ---------------------------------------------------------------------------
424
425 #[derive(Debug)]
426 enum AuthError {
427 Russh(russh::Error),
428 /// All authentication methods we tried were rejected by the server.
429 NoMethodsSucceeded,
430 }
431
432 impl std::fmt::Display for AuthError {
433 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
434 match self {
435 AuthError::Russh(e) => write!(f, "{e}"),
436 AuthError::NoMethodsSucceeded => f.write_str("no SSH authentication method succeeded"),
437 }
438 }
439 }
440
441 impl From<russh::Error> for AuthError {
442 fn from(e: russh::Error) -> Self {
443 AuthError::Russh(e)
444 }
445 }
446
447 /// Outcome of the first authentication phase (agent → keys → auth_none
448 /// probe → supplied password). If we return `NeedsPrompt`, the caller
449 /// must re-acquire the GIL, call `_config.get_auth_password`, and invoke
450 /// [`try_password_phase`] to finish authenticating.
451 enum AuthPhaseOutcome {
452 Authenticated,
453 NeedsPrompt,
454 }
455
456 /// Phase 1: agent → key files → `auth_none` probe → supplied password.
457 ///
458 /// Matches paramiko.py:68-126. Returns `NeedsPrompt` when the server
459 /// advertises `password` / `keyboard-interactive` but we haven't
460 /// authenticated yet, so the caller can solicit a password.
461 async fn authenticate_pre_prompt(
462 session: &mut russh::client::Handle<VerifyingHandler>,
463 user: &str,
464 password: Option<&str>,
465 key_files: &[russh::keys::PrivateKey],
466 ) -> Result<AuthPhaseOutcome, AuthError> {
467 if try_agent_auth(session, user).await? {
468 return Ok(AuthPhaseOutcome::Authenticated);
469 }
470
471 if try_keyfile_auth(session, user, key_files).await? {
472 return Ok(AuthPhaseOutcome::Authenticated);
473 }
474
475 // auth_none probe: unlikely to succeed, but its `remaining_methods`
476 // tells us whether password-style auth is even accepted. If it's not,
477 // paramiko.py:116 raises ConnectionError — we mirror that by bailing
478 // out with `NoMethodsSucceeded`.
479 let remaining = match session.authenticate_none(user.to_string()).await? {
480 russh::client::AuthResult::Success => return Ok(AuthPhaseOutcome::Authenticated),
481 russh::client::AuthResult::Failure {
482 remaining_methods, ..
483 } => remaining_methods,
484 };
485 if !password_style_accepted(&remaining) {
486 log::debug!(
487 "server does not accept password or keyboard-interactive; remaining: {:?}",
488 remaining
489 );
490 return Err(AuthError::NoMethodsSucceeded);
491 }
492
493 // Try the explicitly-supplied password first, so a caller that passes
494 // one doesn't also get a prompt.
495 if let Some(pw) = password {
496 if try_password_or_interactive(session, user, pw).await? {
497 return Ok(AuthPhaseOutcome::Authenticated);
498 }
499 }
500
501 Ok(AuthPhaseOutcome::NeedsPrompt)
502 }
503
504 /// Phase 3: try a password obtained from `_config.get_auth_password`.
505 async fn try_password_phase(
506 session: &mut russh::client::Handle<VerifyingHandler>,
507 user: &str,
508 password: &str,
509 ) -> Result<(), AuthError> {
510 if try_password_or_interactive(session, user, password).await? {
511 Ok(())
512 } else {
513 Err(AuthError::NoMethodsSucceeded)
514 }
515 }
516
517 fn password_style_accepted(methods: &russh::MethodSet) -> bool {
518 methods.iter().any(|m| {
519 matches!(
520 m,
521 russh::MethodKind::Password | russh::MethodKind::KeyboardInteractive
522 )
523 })
524 }
525
526 /// Try `authenticate_password`; on failure, fall back to
527 /// `keyboard-interactive` with the password as the sole response. This
528 /// mirrors paramiko's `auth_password` which transparently does the same.
529 async fn try_password_or_interactive(
530 session: &mut russh::client::Handle<VerifyingHandler>,
531 user: &str,
532 password: &str,
533 ) -> Result<bool, AuthError> {
534 match session
535 .authenticate_password(user.to_string(), password)
536 .await?
537 {
538 russh::client::AuthResult::Success => return Ok(true),
539 russh::client::AuthResult::Failure { .. } => {}
540 }
541
542 // Keyboard-interactive fallback. We blindly respond to the first
543 // InfoRequest with one copy of the password per prompt. Servers that
544 // ask anything beyond a password aren't supported (paramiko has the
545 // same limitation — see the XXX at paramiko.py:109).
546 match session
547 .authenticate_keyboard_interactive_start(user.to_string(), None)
548 .await?
549 {
550 russh::client::KeyboardInteractiveAuthResponse::Success => Ok(true),
551 russh::client::KeyboardInteractiveAuthResponse::Failure { .. } => Ok(false),
552 russh::client::KeyboardInteractiveAuthResponse::InfoRequest { prompts, .. } => {
553 let responses = vec![password.to_string(); prompts.len()];
554 match session
555 .authenticate_keyboard_interactive_respond(responses)
556 .await?
557 {
558 russh::client::KeyboardInteractiveAuthResponse::Success => Ok(true),
559 _ => Ok(false),
560 }
561 }
562 }
563 }
564
565 /// Enumerate keys from the SSH agent and try each in turn. Silent no-op
566 /// when the agent is unreachable — matches paramiko's behavior (agent
567 /// failures never block other auth methods). On Unix this uses
568 /// `$SSH_AUTH_SOCK`; on Windows it talks to Pageant.
569 #[cfg(unix)]
570 async fn try_agent_auth(
571 session: &mut russh::client::Handle<VerifyingHandler>,
572 user: &str,
573 ) -> Result<bool, AuthError> {
574 let agent = match russh::keys::agent::client::AgentClient::connect_env().await {
575 Ok(a) => a,
576 Err(e) => {
577 log::debug!("SSH agent unavailable: {e}");
578 return Ok(false);
579 }
580 };
581 try_agent_auth_with(session, user, agent).await
582 }
583
584 #[cfg(windows)]
585 async fn try_agent_auth(
586 session: &mut russh::client::Handle<VerifyingHandler>,
587 user: &str,
588 ) -> Result<bool, AuthError> {
589 // `connect_pageant` in russh 0.54 returns the client directly (no
590 // `Result`); a missing/unreachable Pageant surfaces later when we
591 // actually request identities, where it's already handled as a silent
592 // no-op below.
593 let agent = russh::keys::agent::client::AgentClient::connect_pageant().await;
594 try_agent_auth_with(session, user, agent).await
595 }
596
597 async fn try_agent_auth_with<S>(
598 session: &mut russh::client::Handle<VerifyingHandler>,
599 user: &str,
600 mut agent: russh::keys::agent::client::AgentClient<S>,
601 ) -> Result<bool, AuthError>
602 where
603 S: russh::keys::agent::client::AgentStream + Unpin + Send + 'static,
604 {
605 let identities = match agent.request_identities().await {
606 Ok(ids) => ids,
607 Err(e) => {
608 log::debug!("SSH agent request_identities failed: {e}");
609 return Ok(false);
610 }
611 };
612
613 for key in identities {
614 log::debug!(
615 "Trying SSH agent key {} ({})",
616 key.fingerprint(Default::default()),
617 key.algorithm()
618 );
619 match session
620 .authenticate_publickey_with(user.to_string(), key, None, &mut agent)
621 .await
622 {
623 Ok(auth) if auth.success() => return Ok(true),
624 Ok(_) => continue,
625 Err(e) => {
626 // `authenticate_publickey_with` can fail for signer
627 // problems even while other agent keys might still work.
628 log::debug!("agent key auth attempt failed: {e}");
629 continue;
630 }
631 }
632 }
633 Ok(false)
634 }
635
636 /// Try each preloaded key file in turn. RSA keys negotiate the strongest
637 /// hash algorithm the server advertises (falling back to SHA-1 when the
638 /// server doesn't send `server-sig-algs`).
639 async fn try_keyfile_auth(
640 session: &mut russh::client::Handle<VerifyingHandler>,
641 user: &str,
642 key_files: &[russh::keys::PrivateKey],
643 ) -> Result<bool, AuthError> {
644 if key_files.is_empty() {
645 return Ok(false);
646 }
647
648 // `Some(Some(alg))` = server wants this hash; `Some(None)` = server
649 // only supports SHA-1; `None` = server didn't advertise, try SHA-1.
650 let rsa_hash = session
651 .best_supported_rsa_hash()
652 .await
653 .ok()
654 .flatten()
655 .flatten();
656
657 for key in key_files {
658 let with_hash = russh::keys::PrivateKeyWithHashAlg::new(Arc::new(key.clone()), rsa_hash);
659 log::debug!(
660 "Trying key file ({}) fingerprint {}",
661 key.algorithm(),
662 key.fingerprint(Default::default())
663 );
664 match session
665 .authenticate_publickey(user.to_string(), with_hash)
666 .await
667 {
668 Ok(auth) if auth.success() => return Ok(true),
669 Ok(_) => continue,
670 Err(e) => {
671 log::debug!("key file auth attempt failed: {e}");
672 continue;
673 }
674 }
675 }
676 Ok(false)
677 }
678
679 /// Synchronous helper that loads `~/.ssh/id_rsa` and `~/.ssh/id_dsa`,
680 /// prompting the user via `dromedary._ui.get_password` for a passphrase
681 /// when a key is encrypted. Missing files are silently skipped.
682 ///
683 /// Runs with the GIL held because the passphrase prompt is Python-side.
684 fn load_default_keyfiles(py: Python) -> Vec<russh::keys::PrivateKey> {
685 let Some(home) = home_dir() else {
686 log::debug!("no home directory; skipping key-file auth");
687 return Vec::new();
688 };
689
690 let mut keys = Vec::new();
691 for name in ["id_rsa", "id_dsa"] {
692 let path = home.join(".ssh").join(name);
693 if !path.exists() {
694 continue;
695 }
696 match load_one_keyfile(py, &path) {
697 Ok(Some(k)) => keys.push(k),
698 Ok(None) => {}
699 Err(e) => log::debug!("load key {}: {}", path.display(), e),
700 }
701 }
702 keys
703 }
704
705 /// Load a single private key file, prompting once for a passphrase on
706 /// `KeyIsEncrypted`. Returns `Ok(None)` if the user cancels the prompt or
707 /// the second attempt also fails.
708 fn load_one_keyfile(
709 py: Python,
710 path: &Path,
711 ) -> Result<Option<russh::keys::PrivateKey>, russh::keys::Error> {
712 match russh::keys::load_secret_key(path, None) {
713 Ok(k) => Ok(Some(k)),
714 Err(russh::keys::Error::KeyIsEncrypted) => {
715 let Some(pw) = prompt_key_password(py, path) else {
716 log::debug!(
717 "encrypted key {} skipped (no passphrase provided)",
718 path.display()
719 );
720 return Ok(None);
721 };
722 match russh::keys::load_secret_key(path, Some(&pw)) {
723 Ok(k) => Ok(Some(k)),
724 Err(e) => {
725 log::debug!(
726 "decrypting {} with supplied passphrase failed: {}",
727 path.display(),
728 e
729 );
730 Ok(None)
731 }
732 }
733 }
734 Err(e) => Err(e),
735 }
736 }
737
738 /// Call `dromedary._ui.get_password(prompt, filename=<path>)`, matching
739 /// paramiko.py's prompt format. Returns `None` if the call fails or the
740 /// result is `None`.
741 fn prompt_key_password(py: Python, path: &Path) -> Option<String> {
742 let ui = match py.import("dromedary._ui") {
743 Ok(m) => m,
744 Err(e) => {
745 log::debug!("importing dromedary._ui failed: {e}");
746 return None;
747 }
748 };
749 let kwargs = PyDict::new(py);
750 if let Err(e) = kwargs.set_item("filename", path.display().to_string()) {
751 log::debug!("building get_password kwargs failed: {e}");
752 return None;
753 }
754 let result = ui.call_method(
755 "get_password",
756 ("SSH %(filename)s password",),
757 Some(&kwargs),
758 );
759 match result {
760 Ok(v) if v.is_none() => None,
761 Ok(v) => v.extract::<String>().ok(),
762 Err(e) => {
763 log::debug!("_ui.get_password raised: {e}");
764 None
765 }
766 }
767 }
768
769 /// Resolve a default username via `dromedary._config.get_auth_user("ssh",
770 /// host, port=port, default=getpass.getuser())`, falling back to `$USER`
771 /// if the Python layer is unavailable. Mirrors paramiko.py:64-67.
772 fn resolve_username(py: Python, host: &str, port: Option<u16>) -> String {
773 let fallback = whoami_or_default();
774 let cfg = match py.import("dromedary._config") {
775 Ok(m) => m,
776 Err(e) => {
777 log::debug!("importing dromedary._config failed: {e}");
778 return fallback;
779 }
780 };
781 let kwargs = PyDict::new(py);
782 if let Err(e) = kwargs.set_item("default", &fallback) {
783 log::debug!("building get_auth_user kwargs failed: {e}");
784 return fallback;
785 }
786 if let Some(p) = port {
787 if let Err(e) = kwargs.set_item("port", p) {
788 log::debug!("building get_auth_user kwargs failed: {e}");
789 return fallback;
790 }
791 }
792 match cfg.call_method("get_auth_user", ("ssh", host), Some(&kwargs)) {
793 Ok(v) if v.is_none() => fallback,
794 Ok(v) => v.extract::<String>().unwrap_or(fallback),
795 Err(e) => {
796 log::debug!("_config.get_auth_user raised: {e}");
797 fallback
798 }
799 }
800 }
801
802 /// Prompt for an auth password via `dromedary._config.get_auth_password(
803 /// "ssh", host, user, port=port)`. Returns `None` if the call fails or
804 /// the user cancels.
805 fn prompt_auth_password(py: Python, host: &str, port: Option<u16>, user: &str) -> Option<String> {
806 let cfg = match py.import("dromedary._config") {
807 Ok(m) => m,
808 Err(e) => {
809 log::debug!("importing dromedary._config failed: {e}");
810 return None;
811 }
812 };
813 let kwargs = PyDict::new(py);
814 if let Some(p) = port {
815 if let Err(e) = kwargs.set_item("port", p) {
816 log::debug!("building get_auth_password kwargs failed: {e}");
817 return None;
818 }
819 }
820 match cfg.call_method("get_auth_password", ("ssh", host, user), Some(&kwargs)) {
821 Ok(v) if v.is_none() => None,
822 Ok(v) => v.extract::<String>().ok(),
823 Err(e) => {
824 log::debug!("_config.get_auth_password raised: {e}");
825 None
826 }
827 }
828 }
829
830 fn home_dir() -> Option<PathBuf> {
831 std::env::var_os("HOME").map(PathBuf::from)
832 }
833
834 /// `~/.ssh/known_hosts` (on Windows: `~/ssh/known_hosts` — matches
835 /// russh's own `known_hosts_path`). Falls back to a sentinel path inside
836 /// a non-existent temp dir when `$HOME` is unset; `check_known_hosts_path`
837 /// returns `Ok(false)` on missing files so this is harmless.
838 fn system_known_hosts_path() -> PathBuf {
839 match home_dir() {
840 Some(h) => {
841 if cfg!(windows) {
842 h.join("ssh").join("known_hosts")
843 } else {
844 h.join(".ssh").join("known_hosts")
845 }
846 }
847 None => PathBuf::from("/nonexistent/known_hosts"),
848 }
849 }
850
851 /// Resolve `<dromedary._bedding.config_dir()>/ssh_host_keys` via the
852 /// Python side so embedder overrides are honored. Also calls
853 /// `_bedding.ensure_config_dir_exists()` so the later `learn_*` write
854 /// doesn't fail on a missing parent directory.
855 fn dromedary_host_keys_path(py: Python) -> PathBuf {
856 let fallback = || {
857 let xdg = std::env::var_os("XDG_CONFIG_HOME")
858 .map(PathBuf::from)
859 .or_else(|| home_dir().map(|h| h.join(".config")))
860 .unwrap_or_else(|| PathBuf::from("."));
861 xdg.join("breezy").join("ssh_host_keys")
862 };
863 let bedding = match py.import("dromedary._bedding") {
864 Ok(m) => m,
865 Err(e) => {
866 log::debug!("importing dromedary._bedding failed: {e}");
867 return fallback();
868 }
869 };
870 if let Err(e) = bedding.call_method0("ensure_config_dir_exists") {
871 log::debug!("ensure_config_dir_exists failed: {e}");
872 }
873 match bedding.call_method0("config_dir") {
874 Ok(v) => match v.extract::<String>() {
875 Ok(s) => PathBuf::from(s).join("ssh_host_keys"),
876 Err(e) => {
877 log::debug!("config_dir() returned non-string: {e}");
878 fallback()
879 }
880 },
881 Err(e) => {
882 log::debug!("_bedding.config_dir() raised: {e}");
883 fallback()
884 }
885 }
886 }
887
888 #[pymethods]
889 impl RusshVendor {
890 #[new]
891 fn new() -> Self {
892 Self
893 }
894
895 /// Open an SFTP session. Returns a fully-constructed `SFTPClient` that
896 /// the caller can use directly (same object as `_transport_rs.sftp.
897 /// SFTPClient`).
898 #[pyo3(signature = (username, password, host, port=None))]
899 fn connect_sftp(
900 &self,
901 py: Python,
902 username: Option<&str>,
903 password: Option<&str>,
904 host: &str,
905 port: Option<u16>,
906 ) -> PyResult<SFTPClient> {
907 let (runtime, handle) = Self::connect(py, username, password, host, port)?;
908
909 py.detach(move || {
910 let (runtime_for_stream, stream) = runtime.block_on({
911 let runtime = runtime.clone();
912 async move {
913 let channel = handle
914 .channel_open_session()
915 .await
916 .map_err(|e| PyRuntimeError::new_err(format!("open session: {e}")))?;
917 channel.request_subsystem(true, "sftp").await.map_err(|e| {
918 PyRuntimeError::new_err(format!("request sftp subsystem: {e}"))
919 })?;
920 Ok::<_, PyErr>((runtime, channel.into_stream()))
921 }
922 })?;
923
924 let channel: BoxedChannel = Box::new(BlockingChannel {
925 runtime: runtime_for_stream,
926 stream,
927 });
928 SFTPClient::from_channel(channel)
929 .map_err(|e| PyRuntimeError::new_err(format!("sftp init: {e}")))
930 })
931 }
932
933 /// Execute a remote command and return a connection whose `send` / `recv`
934 /// drive the command's stdio. Parallels paramiko's
935 /// `_ParamikoSSHConnection`.
936 #[pyo3(signature = (username, password, host, command, port=None))]
937 fn connect_ssh(
938 &self,
939 py: Python,
940 username: Option<&str>,
941 password: Option<&str>,
942 host: &str,
943 command: Vec<String>,
944 port: Option<u16>,
945 ) -> PyResult<RusshSSHConnection> {
946 let (runtime, handle) = Self::connect(py, username, password, host, port)?;
947
948 py.detach(move || {
949 let (runtime_for_stream, stream) = runtime.block_on({
950 let runtime = runtime.clone();
951 async move {
952 let channel = handle
953 .channel_open_session()
954 .await
955 .map_err(|e| PyRuntimeError::new_err(format!("open session: {e}")))?;
956 let cmdline = command.join(" ");
957 channel
958 .exec(true, cmdline.as_str())
959 .await
960 .map_err(|e| PyRuntimeError::new_err(format!("exec: {e}")))?;
961 Ok::<_, PyErr>((runtime, channel.into_stream()))
962 }
963 })?;
964
965 Ok(RusshSSHConnection {
966 inner: Mutex::new(Some(BlockingChannel {
967 runtime: runtime_for_stream,
968 stream,
969 })),
970 })
971 })
972 }
973 }
974
975 /// Minimal fallback when no username is supplied. `_config.get_auth_user`
976 /// on the Python side gives a richer lookup; 5e wires that in. For now use
977 /// the `$USER` env var or "unknown".
978 fn whoami_or_default() -> String {
979 std::env::var("USER").unwrap_or_else(|_| "unknown".to_string())
980 }
981
982 pub(crate) fn register(_py: Python, m: &Bound<PyModule>) -> PyResult<()> {
983 m.add_class::<RusshVendor>()?;
984 m.add_class::<RusshSSHConnection>()?;
985 Ok(())
986 }