remotefs_ssh/ssh/backend/
libssh2.rs

1use std::io::{Read, Seek, Write};
2use std::net::{SocketAddr, TcpStream, ToSocketAddrs as _};
3use std::path::{Path, PathBuf};
4use std::str::FromStr as _;
5use std::time::{Duration, SystemTime};
6
7use remotefs::fs::stream::{ReadAndSeek, WriteAndSeek};
8use remotefs::fs::{FileType, Metadata, ReadStream, UnixPex, WriteStream};
9use remotefs::{File, RemoteError, RemoteErrorType, RemoteResult};
10use ssh2::{FileStat, OpenType, RenameFlags};
11
12use super::SshSession;
13use crate::ssh::backend::Sftp;
14use crate::ssh::config::Config;
15use crate::{SshAgentIdentity, SshOpts};
16
17/// An implementation of [`SshSession`] using libssh2 as the backend.
18pub struct LibSsh2Session {
19    session: ssh2::Session,
20}
21
22/// A wrapper around [`ssh2::Sftp`] to provide a SFTP client for [`LibSsh2Session`]
23pub struct LibSsh2Sftp {
24    inner: ssh2::Sftp,
25}
26
27/// Authentication method
28#[derive(Debug, Clone, PartialEq, Eq)]
29enum Authentication {
30    RsaKey(PathBuf),
31    Password(String),
32}
33
34impl SshSession for LibSsh2Session {
35    type Sftp = LibSsh2Sftp;
36
37    fn connect(opts: &SshOpts) -> RemoteResult<Self> {
38        // parse configuration
39        let ssh_config = Config::try_from(opts)?;
40        // Resolve host
41        debug!("Connecting to '{}'", ssh_config.address);
42        // setup tcp stream
43        let socket_addresses: Vec<SocketAddr> = match ssh_config.address.to_socket_addrs() {
44            Ok(s) => s.collect(),
45            Err(err) => {
46                return Err(RemoteError::new_ex(
47                    RemoteErrorType::BadAddress,
48                    err.to_string(),
49                ));
50            }
51        };
52        let mut stream = None;
53        for _ in 0..ssh_config.connection_attempts {
54            for socket_addr in socket_addresses.iter() {
55                trace!(
56                    "Trying to connect to socket address '{}' (timeout: {}s)",
57                    socket_addr,
58                    ssh_config.connection_timeout.as_secs()
59                );
60                if let Ok(tcp_stream) = tcp_connect(socket_addr, ssh_config.connection_timeout) {
61                    debug!("Connection established with address {socket_addr}");
62                    stream = Some(tcp_stream);
63                    break;
64                }
65            }
66            // break from attempts cycle if some
67            if stream.is_some() {
68                break;
69            }
70        }
71        // If stream is None, return connection timeout
72        let stream = match stream {
73            Some(s) => s,
74            None => {
75                error!("No suitable socket address found; connection timeout");
76                return Err(RemoteError::new_ex(
77                    RemoteErrorType::ConnectionError,
78                    "connection timeout",
79                ));
80            }
81        };
82        // Create session
83        let mut session = match ssh2::Session::new() {
84            Ok(s) => s,
85            Err(err) => {
86                error!("Could not create session: {err}");
87                return Err(RemoteError::new_ex(RemoteErrorType::ConnectionError, err));
88            }
89        };
90        // Set TCP stream
91        session.set_tcp_stream(stream);
92        // configure algos
93        set_algo_prefs(&mut session, opts, &ssh_config)?;
94        // Open connection and initialize handshake
95        if let Err(err) = session.handshake() {
96            error!("SSH handshake failed: {err}");
97            return Err(RemoteError::new_ex(RemoteErrorType::ProtocolError, err));
98        }
99
100        // if use_ssh_agent is enabled, try to authenticate with ssh agent
101        if let Some(ssh_agent_config) = &opts.ssh_agent_identity {
102            match session_auth_with_agent(&mut session, &ssh_config.username, ssh_agent_config) {
103                Ok(_) => {
104                    info!("Authenticated with ssh agent");
105                    return Ok(Self { session });
106                }
107                Err(err) => {
108                    error!("Could not authenticate with ssh agent: {err}");
109                }
110            }
111        }
112
113        // Authenticate with password or key
114        if !session.authenticated() {
115            let mut methods = vec![];
116            // first try with ssh agent
117            if let Some(rsa_key) = opts.key_storage.as_ref().and_then(|x| {
118                x.resolve(ssh_config.host.as_str(), ssh_config.username.as_str())
119                    .or(x.resolve(
120                        ssh_config.resolved_host.as_str(),
121                        ssh_config.username.as_str(),
122                    ))
123            }) {
124                methods.push(Authentication::RsaKey(rsa_key.clone()));
125            }
126            // then try with password
127            if let Some(password) = opts.password.as_ref() {
128                methods.push(Authentication::Password(password.clone()));
129            }
130
131            // try with methods
132            let mut last_err = None;
133            for auth_method in methods {
134                match session_auth(&mut session, opts, &ssh_config, auth_method) {
135                    Ok(_) => {
136                        info!("Authenticated successfully");
137                        return Ok(Self { session });
138                    }
139                    Err(err) => {
140                        error!("Authentication failed: {err}",);
141                        last_err = Some(err);
142                    }
143                }
144            }
145
146            return Err(match last_err {
147                Some(err) => err,
148                None => RemoteError::new_ex(
149                    RemoteErrorType::AuthenticationFailed,
150                    "no authentication method provided",
151                ),
152            });
153        }
154
155        Ok(Self { session })
156    }
157
158    fn disconnect(&self) -> RemoteResult<()> {
159        self.session
160            .disconnect(None, "Mandi!", None)
161            .map_err(|err| RemoteError::new_ex(RemoteErrorType::ConnectionError, err))
162    }
163
164    fn authenticated(&self) -> RemoteResult<bool> {
165        Ok(self.session.authenticated())
166    }
167
168    fn banner(&self) -> RemoteResult<Option<String>> {
169        Ok(self.session.banner().map(String::from))
170    }
171
172    fn cmd<S>(&mut self, cmd: S) -> RemoteResult<(u32, String)>
173    where
174        S: AsRef<str>,
175    {
176        let output = perform_shell_cmd(&mut self.session, format!("{}; echo $?", cmd.as_ref()))?;
177        if let Some(index) = output.trim().rfind('\n') {
178            trace!("Read from stdout: '{output}'");
179            let actual_output = (output[0..index + 1]).to_string();
180            trace!("Actual output '{actual_output}'");
181            trace!("Parsing return code '{}'", output[index..].trim());
182            let rc = match u32::from_str(output[index..].trim()).ok() {
183                Some(val) => val,
184                None => {
185                    return Err(RemoteError::new_ex(
186                        RemoteErrorType::ProtocolError,
187                        "Failed to get command exit code",
188                    ));
189                }
190            };
191            debug!(r#"Command output: "{actual_output}"; exit code: {rc}"#);
192            Ok((rc, actual_output))
193        } else {
194            match u32::from_str(output.trim()).ok() {
195                Some(val) => Ok((val, String::new())),
196                None => Err(RemoteError::new_ex(
197                    RemoteErrorType::ProtocolError,
198                    "Failed to get command exit code",
199                )),
200            }
201        }
202    }
203
204    fn scp_recv(&self, path: &Path) -> RemoteResult<Box<dyn Read + Send>> {
205        self.session.set_blocking(true);
206
207        self.session
208            .scp_recv(path)
209            .map(|(reader, _stat)| Box::new(reader) as Box<dyn Read + Send>)
210            .map_err(|err| {
211                RemoteError::new_ex(
212                    RemoteErrorType::ProtocolError,
213                    format!("Could not receive file over SCP: {err}"),
214                )
215            })
216    }
217
218    fn scp_send(
219        &self,
220        remote_path: &Path,
221        mode: i32,
222        size: u64,
223        times: Option<(u64, u64)>,
224    ) -> RemoteResult<Box<dyn Write + Send>> {
225        self.session.set_blocking(true);
226
227        self.session
228            .scp_send(remote_path, mode, size, times)
229            .map(|writer| Box::new(writer) as Box<dyn Write + Send>)
230            .map_err(|err| {
231                RemoteError::new_ex(
232                    RemoteErrorType::ProtocolError,
233                    format!("Could not send file over SCP: {err}"),
234                )
235            })
236    }
237
238    fn sftp(&self) -> RemoteResult<Self::Sftp> {
239        self.session.set_blocking(true);
240
241        Ok(LibSsh2Sftp {
242            inner: self.session.sftp().map_err(|err| {
243                RemoteError::new_ex(
244                    RemoteErrorType::ProtocolError,
245                    format!("Could not create SFTP session: {err}"),
246                )
247            })?,
248        })
249    }
250}
251
252struct SftpFileReader(ssh2::File);
253
254struct SftpFileWriter(ssh2::File);
255
256impl Write for SftpFileWriter {
257    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
258        self.0.write(buf)
259    }
260
261    fn flush(&mut self) -> std::io::Result<()> {
262        self.0.flush()
263    }
264}
265
266impl Seek for SftpFileWriter {
267    fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
268        self.0.seek(pos)
269    }
270}
271
272impl WriteAndSeek for SftpFileWriter {}
273
274impl Read for SftpFileReader {
275    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
276        self.0.read(buf)
277    }
278}
279
280impl Seek for SftpFileReader {
281    fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
282        self.0.seek(pos)
283    }
284}
285
286impl ReadAndSeek for SftpFileReader {}
287
288impl Sftp for LibSsh2Sftp {
289    fn mkdir(&self, path: &Path, mode: i32) -> RemoteResult<()> {
290        self.inner.mkdir(path, mode).map_err(|err| {
291            RemoteError::new_ex(
292                RemoteErrorType::FileCreateDenied,
293                format!(
294                    "Could not create directory '{path}': {err}",
295                    path = path.display()
296                ),
297            )
298        })
299    }
300
301    fn open_read(&self, path: &Path) -> RemoteResult<ReadStream> {
302        self.inner
303            .open(path)
304            .map(|file| ReadStream::from(Box::new(SftpFileReader(file)) as Box<dyn ReadAndSeek>))
305            .map_err(|err| {
306                RemoteError::new_ex(
307                    RemoteErrorType::ProtocolError,
308                    format!(
309                        "Could not open file at '{path}': {err}",
310                        path = path.display()
311                    ),
312                )
313            })
314    }
315
316    fn open_write(
317        &self,
318        path: &Path,
319        flags: super::WriteMode,
320        mode: i32,
321    ) -> RemoteResult<WriteStream> {
322        let flags = match flags {
323            super::WriteMode::Append => {
324                ssh2::OpenFlags::WRITE | ssh2::OpenFlags::APPEND | ssh2::OpenFlags::CREATE
325            }
326            super::WriteMode::Truncate => {
327                ssh2::OpenFlags::WRITE | ssh2::OpenFlags::CREATE | ssh2::OpenFlags::TRUNCATE
328            }
329        };
330
331        self.inner
332            .open_mode(path, flags, mode, OpenType::File)
333            .map(|file| WriteStream::from(Box::new(SftpFileWriter(file)) as Box<dyn WriteAndSeek>))
334            .map_err(|err| {
335                RemoteError::new_ex(
336                    RemoteErrorType::ProtocolError,
337                    format!(
338                        "Could not open file at '{path}': {err}",
339                        path = path.display()
340                    ),
341                )
342            })
343    }
344
345    fn readdir<T>(&self, dirname: T) -> RemoteResult<Vec<remotefs::File>>
346    where
347        T: AsRef<Path>,
348    {
349        self.inner
350            .readdir(dirname)
351            .map(|files| {
352                files
353                    .into_iter()
354                    .map(|(path, metadata)| self.make_fsentry(path.as_path(), &metadata))
355                    .collect()
356            })
357            .map_err(|err| {
358                RemoteError::new_ex(
359                    RemoteErrorType::ProtocolError,
360                    format!("Could not read directory: {err}",),
361                )
362            })
363    }
364
365    fn realpath(&self, path: &Path) -> RemoteResult<PathBuf> {
366        self.inner.realpath(path).map_err(|err| {
367            RemoteError::new_ex(
368                RemoteErrorType::ProtocolError,
369                format!(
370                    "Could not resolve real path for '{path}': {err}",
371                    path = path.display()
372                ),
373            )
374        })
375    }
376
377    fn rename(&self, src: &Path, dest: &Path) -> RemoteResult<()> {
378        self.inner
379            .rename(src, dest, Some(RenameFlags::OVERWRITE))
380            .map_err(|err| {
381                RemoteError::new_ex(
382                    RemoteErrorType::ProtocolError,
383                    format!("Could not rename file '{src}': {err}", src = src.display()),
384                )
385            })
386    }
387
388    fn rmdir(&self, path: &Path) -> RemoteResult<()> {
389        self.inner.rmdir(path).map_err(|err| {
390            RemoteError::new_ex(
391                RemoteErrorType::CouldNotRemoveFile,
392                format!(
393                    "Could not remove directory '{path}': {err}",
394                    path = path.display()
395                ),
396            )
397        })
398    }
399
400    fn setstat(&self, path: &Path, metadata: Metadata) -> RemoteResult<()> {
401        self.inner
402            .setstat(path, Self::metadata_to_filestat(metadata))
403            .map_err(|err| {
404                RemoteError::new_ex(
405                    RemoteErrorType::ProtocolError,
406                    format!(
407                        "Could not set file attributes for '{path}': {err}",
408                        path = path.display()
409                    ),
410                )
411            })
412    }
413
414    fn stat(&self, filename: &Path) -> RemoteResult<File> {
415        self.inner
416            .stat(filename)
417            .map(|metadata| self.make_fsentry(filename, &metadata))
418            .map_err(|err| {
419                RemoteError::new_ex(
420                    RemoteErrorType::ProtocolError,
421                    format!(
422                        "Could not get file attributes for '{filename}': {err}",
423                        filename = filename.display()
424                    ),
425                )
426            })
427    }
428
429    fn symlink(&self, path: &Path, target: &Path) -> RemoteResult<()> {
430        self.inner.symlink(path, target).map_err(|err| {
431            RemoteError::new_ex(
432                RemoteErrorType::FileCreateDenied,
433                format!(
434                    "Could not create symlink '{path}': {err}",
435                    path = path.display()
436                ),
437            )
438        })
439    }
440
441    fn unlink(&self, path: &Path) -> RemoteResult<()> {
442        self.inner.unlink(path).map_err(|err| {
443            RemoteError::new_ex(
444                RemoteErrorType::CouldNotRemoveFile,
445                format!(
446                    "Could not remove file '{path}': {err}",
447                    path = path.display()
448                ),
449            )
450        })
451    }
452}
453
454impl LibSsh2Sftp {
455    fn metadata_to_filestat(metadata: Metadata) -> FileStat {
456        let atime = metadata
457            .accessed
458            .and_then(|x| x.duration_since(SystemTime::UNIX_EPOCH).ok())
459            .map(|x| x.as_secs());
460        let mtime = metadata
461            .modified
462            .and_then(|x| x.duration_since(SystemTime::UNIX_EPOCH).ok())
463            .map(|x| x.as_secs());
464        FileStat {
465            size: Some(metadata.size),
466            uid: metadata.uid,
467            gid: metadata.gid,
468            perm: metadata.mode.map(u32::from),
469            atime,
470            mtime,
471        }
472    }
473
474    fn make_fsentry(&self, path: &Path, metadata: &FileStat) -> File {
475        let name = match path.file_name() {
476            None => "/".to_string(),
477            Some(name) => name.to_string_lossy().to_string(),
478        };
479        debug!("Found file {name}");
480        // parse metadata
481        let uid = metadata.uid;
482        let gid = metadata.gid;
483        let mode = metadata.perm.map(UnixPex::from);
484        let size = metadata.size.unwrap_or(0);
485        let accessed = metadata.atime.map(|x| {
486            SystemTime::UNIX_EPOCH
487                .checked_add(Duration::from_secs(x))
488                .unwrap_or(SystemTime::UNIX_EPOCH)
489        });
490        let modified = metadata.mtime.map(|x| {
491            SystemTime::UNIX_EPOCH
492                .checked_add(Duration::from_secs(x))
493                .unwrap_or(SystemTime::UNIX_EPOCH)
494        });
495        let symlink = match metadata.file_type().is_symlink() {
496            false => None,
497            true => match self.inner.readlink(path) {
498                Ok(p) => Some(p),
499                Err(err) => {
500                    error!(
501                        "Failed to read link of {} (even it's supposed to be a symlink): {}",
502                        path.display(),
503                        err
504                    );
505                    None
506                }
507            },
508        };
509        let file_type = if symlink.is_some() {
510            FileType::Symlink
511        } else if metadata.is_dir() {
512            FileType::Directory
513        } else {
514            FileType::File
515        };
516        let entry_metadata = Metadata {
517            accessed,
518            created: None,
519            file_type,
520            gid,
521            mode,
522            modified,
523            size,
524            symlink,
525            uid,
526        };
527        trace!("Metadata for {}: {:?}", path.display(), entry_metadata);
528        File {
529            path: path.to_path_buf(),
530            metadata: entry_metadata,
531        }
532    }
533}
534
535fn perform_shell_cmd<S: AsRef<str>>(session: &mut ssh2::Session, cmd: S) -> RemoteResult<String> {
536    // Create channel
537    trace!("Running command: {}", cmd.as_ref());
538    let mut channel = match session.channel_session() {
539        Ok(ch) => ch,
540        Err(err) => {
541            return Err(RemoteError::new_ex(
542                RemoteErrorType::ProtocolError,
543                format!("Could not open channel: {err}"),
544            ));
545        }
546    };
547    // Execute command
548    if let Err(err) = channel.exec(cmd.as_ref()) {
549        return Err(RemoteError::new_ex(
550            RemoteErrorType::ProtocolError,
551            format!("Could not execute command \"{}\": {}", cmd.as_ref(), err),
552        ));
553    }
554    // Read output
555    let mut output: String = String::new();
556    match channel.read_to_string(&mut output) {
557        Ok(_) => {
558            // Wait close
559            let _ = channel.wait_close();
560            trace!("Command output: {output}");
561            Ok(output)
562        }
563        Err(err) => Err(RemoteError::new_ex(
564            RemoteErrorType::ProtocolError,
565            format!("Could not read output: {err}"),
566        )),
567    }
568}
569
570/// connect to socket address with provided timeout.
571/// If timeout is zero, don't set timeout
572fn tcp_connect(address: &SocketAddr, timeout: Duration) -> std::io::Result<TcpStream> {
573    if timeout.is_zero() {
574        TcpStream::connect(address)
575    } else {
576        TcpStream::connect_timeout(address, timeout)
577    }
578}
579
580/// Configure algorithm preferences into session
581fn set_algo_prefs(
582    session: &mut ssh2::Session,
583    opts: &SshOpts,
584    config: &Config,
585) -> RemoteResult<()> {
586    // Configure preferences from config
587    let params = &config.params;
588    trace!("Configuring algorithm preferences...");
589    if let Some(compress) = params.compression {
590        trace!("compression: {compress}");
591        session.set_compress(compress);
592    }
593
594    // kex
595    let algos = params.kex_algorithms.algorithms().join(",");
596    trace!("Configuring KEX algorithms: {algos}");
597    if let Err(err) = session.method_pref(ssh2::MethodType::Kex, algos.as_str()) {
598        error!("Could not set KEX algorithms: {err}");
599        return Err(RemoteError::new_ex(RemoteErrorType::ProtocolError, err));
600    }
601
602    // HostKey
603    let algos = params.host_key_algorithms.algorithms().join(",");
604    trace!("Configuring HostKey algorithms: {algos}");
605    if let Err(err) = session.method_pref(ssh2::MethodType::HostKey, algos.as_str()) {
606        error!("Could not set host key algorithms: {err}");
607        return Err(RemoteError::new_ex(RemoteErrorType::ProtocolError, err));
608    }
609
610    // ciphers
611    let algos = params.ciphers.algorithms().join(",");
612    trace!("Configuring Crypt algorithms: {algos}");
613    if let Err(err) = session.method_pref(ssh2::MethodType::CryptCs, algos.as_str()) {
614        error!("Could not set crypt algorithms (client-server): {err}");
615        return Err(RemoteError::new_ex(RemoteErrorType::ProtocolError, err));
616    }
617    if let Err(err) = session.method_pref(ssh2::MethodType::CryptSc, algos.as_str()) {
618        error!("Could not set crypt algorithms (server-client): {err}");
619        return Err(RemoteError::new_ex(RemoteErrorType::ProtocolError, err));
620    }
621
622    // MAC
623    let algos = params.mac.algorithms().join(",");
624    trace!("Configuring MAC algorithms: {algos}");
625    if let Err(err) = session.method_pref(ssh2::MethodType::MacCs, algos.as_str()) {
626        error!("Could not set MAC algorithms (client-server): {err}");
627        return Err(RemoteError::new_ex(RemoteErrorType::ProtocolError, err));
628    }
629    if let Err(err) = session.method_pref(ssh2::MethodType::MacSc, algos.as_str()) {
630        error!("Could not set MAC algorithms (server-client): {err}");
631        return Err(RemoteError::new_ex(RemoteErrorType::ProtocolError, err));
632    }
633
634    // -- configure algos from opts
635    for method in opts.methods.iter() {
636        let algos = method.prefs();
637        trace!("Configuring {:?} algorithm: {}", method.method_type, algos);
638        if let Err(err) = session.method_pref(method.method_type.into(), algos.as_str()) {
639            error!("Could not set {:?} algorithms: {}", method.method_type, err);
640            return Err(RemoteError::new_ex(RemoteErrorType::ProtocolError, err));
641        }
642    }
643    Ok(())
644}
645
646/// Authenticate on session with ssh agent
647fn session_auth_with_agent(
648    session: &mut ssh2::Session,
649    username: &str,
650    ssh_agent_config: &SshAgentIdentity,
651) -> RemoteResult<()> {
652    let mut agent = session
653        .agent()
654        .map_err(|err| RemoteError::new_ex(RemoteErrorType::ConnectionError, err))?;
655
656    agent
657        .connect()
658        .map_err(|err| RemoteError::new_ex(RemoteErrorType::ConnectionError, err))?;
659
660    agent
661        .list_identities()
662        .map_err(|err| RemoteError::new_ex(RemoteErrorType::ConnectionError, err))?;
663
664    let mut connection_result = Err(RemoteError::new(RemoteErrorType::AuthenticationFailed));
665
666    for identity in agent
667        .identities()
668        .map_err(|err| RemoteError::new_ex(RemoteErrorType::ConnectionError, err))?
669    {
670        if ssh_agent_config.pubkey_matches(identity.blob()) {
671            debug!("Trying to authenticate with ssh agent with key: {identity:?}");
672        } else {
673            continue;
674        }
675        match agent.userauth(username, &identity) {
676            Ok(()) => {
677                connection_result = Ok(());
678                debug!("Authenticated with ssh agent with key: {identity:?}");
679                break;
680            }
681            Err(err) => {
682                debug!("SSH agent auth failed: {err}");
683                connection_result = Err(RemoteError::new_ex(
684                    RemoteErrorType::AuthenticationFailed,
685                    err,
686                ));
687            }
688        }
689    }
690
691    if let Err(err) = agent.disconnect() {
692        warn!("Could not disconnect from ssh agent: {err}");
693    }
694
695    connection_result
696}
697
698/// Authenticate on session with private key
699fn session_auth_with_rsakey(
700    session: &mut ssh2::Session,
701    username: &str,
702    private_key: &Path,
703    password: Option<&str>,
704    identity_file: Option<&[PathBuf]>,
705) -> RemoteResult<()> {
706    debug!("Authenticating with username '{username}' and RSA key");
707    let mut keys = vec![private_key];
708    if let Some(identity_file) = identity_file {
709        let other_keys: Vec<&Path> = identity_file.iter().map(|x| x.as_path()).collect();
710        keys.extend(other_keys);
711    }
712    // iterate over keys
713    for key in keys.into_iter() {
714        trace!("Trying to authenticate with RSA key at '{}'", key.display());
715        match session.userauth_pubkey_file(username, None, key, password) {
716            Ok(_) => {
717                debug!("Authenticated with key at '{}'", key.display());
718                return Ok(());
719            }
720            Err(err) => {
721                error!("Authentication failed: {err}");
722            }
723        }
724    }
725    Err(RemoteError::new_ex(
726        RemoteErrorType::AuthenticationFailed,
727        "could not find any suitable RSA key to authenticate with",
728    ))
729}
730
731/// Authenticate on session with the provided [`Authentication`] method.
732fn session_auth(
733    session: &mut ssh2::Session,
734    opts: &SshOpts,
735    ssh_config: &Config,
736    authentication: Authentication,
737) -> RemoteResult<()> {
738    match authentication {
739        Authentication::RsaKey(private_key) => session_auth_with_rsakey(
740            session,
741            &ssh_config.username,
742            private_key.as_path(),
743            opts.password.as_deref(),
744            ssh_config.params.identity_file.as_deref(),
745        ),
746        Authentication::Password(password) => {
747            session_auth_with_password(session, &ssh_config.username, &password)
748        }
749    }
750}
751
752/// Authenticate on session with username and password
753fn session_auth_with_password(
754    session: &mut ssh2::Session,
755    username: &str,
756    password: &str,
757) -> RemoteResult<()> {
758    // Username / password
759    debug!("Authenticating with username '{username}' and password");
760    if let Err(err) = session.userauth_password(username, password) {
761        error!("Authentication failed: {err}");
762        Err(RemoteError::new_ex(
763            RemoteErrorType::AuthenticationFailed,
764            err,
765        ))
766    } else {
767        Ok(())
768    }
769}
770
771#[cfg(test)]
772mod test {
773
774    use ssh2_config::ParseRule;
775
776    use super::*;
777    use crate::mock::ssh as ssh_mock;
778
779    #[test]
780    fn should_connect_to_ssh_server_auth_user_password() {
781        use crate::ssh::container::OpensshServer;
782
783        let container = OpensshServer::start();
784        let port = container.port();
785
786        crate::mock::logger();
787        let config_file = ssh_mock::create_ssh_config(port);
788        let opts = SshOpts::new("sftp")
789            .config_file(config_file.path(), ParseRule::ALLOW_UNKNOWN_FIELDS)
790            .password("password");
791
792        if let Err(err) = LibSsh2Session::connect(&opts) {
793            panic!("Could not connect to server: {err}");
794        }
795        let session = LibSsh2Session::connect(&opts).unwrap();
796        assert!(session.authenticated().unwrap());
797
798        drop(container);
799    }
800
801    #[test]
802    fn should_connect_to_ssh_server_auth_key() {
803        use crate::ssh::container::OpensshServer;
804
805        let container = OpensshServer::start();
806        let port = container.port();
807
808        crate::mock::logger();
809        let config_file = ssh_mock::create_ssh_config(port);
810        let opts = SshOpts::new("sftp")
811            .config_file(config_file.path(), ParseRule::ALLOW_UNKNOWN_FIELDS)
812            .key_storage(Box::new(ssh_mock::MockSshKeyStorage::default()));
813        let session = LibSsh2Session::connect(&opts).unwrap();
814        assert!(session.authenticated().unwrap());
815    }
816
817    #[test]
818
819    fn should_perform_shell_command_on_server() {
820        crate::mock::logger();
821        let container = crate::ssh::container::OpensshServer::start();
822        let port = container.port();
823
824        let opts = SshOpts::new("127.0.0.1")
825            .port(port)
826            .username("sftp")
827            .password("password");
828        let mut session = LibSsh2Session::connect(&opts).unwrap();
829        assert!(session.authenticated().unwrap());
830        // run commands
831        assert!(session.cmd("pwd").is_ok());
832    }
833
834    #[test]
835
836    fn should_perform_shell_command_on_server_and_return_exit_code() {
837        crate::mock::logger();
838        let container = crate::ssh::container::OpensshServer::start();
839        let port = container.port();
840
841        let opts = SshOpts::new("127.0.0.1")
842            .port(port)
843            .username("sftp")
844            .password("password");
845        let mut session = LibSsh2Session::connect(&opts).unwrap();
846        assert!(session.authenticated().unwrap());
847        // run commands
848        assert_eq!(
849            session.cmd_at("pwd", Path::new("/tmp")).ok().unwrap(),
850            (0, String::from("/tmp\n"))
851        );
852        assert_eq!(
853            session
854                .cmd_at("pippopluto", Path::new("/tmp"))
855                .ok()
856                .unwrap()
857                .0,
858            127
859        );
860    }
861
862    #[test]
863    fn should_fail_authentication() {
864        crate::mock::logger();
865        let container = crate::ssh::container::OpensshServer::start();
866        let port = container.port();
867
868        let opts = SshOpts::new("127.0.0.1")
869            .port(port)
870            .username("sftp")
871            .password("ippopotamo");
872        assert!(LibSsh2Session::connect(&opts).is_err());
873    }
874
875    #[test]
876    fn test_filetransfer_sftp_bad_server() {
877        crate::mock::logger();
878        let opts = SshOpts::new("myverybad.verybad.server")
879            .port(10022)
880            .username("sftp")
881            .password("ippopotamo");
882        assert!(LibSsh2Session::connect(&opts).is_err());
883    }
884}