1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
// pub(crate) use session_inner::SessionInner;
mod session_broker;
mod session_local;

pub use session_broker::SessionBroker;
pub use session_local::LocalSession;
use tracing::*;

use std::{
    io::{Read, Write},
    net::{TcpStream, ToSocketAddrs},
    path::Path,
    time::Duration,
};

use crate::{
    algorithm::{Compress, Digest, Enc, Kex, Mac, PubKey},
    client::Client,
    config::{algorithm::AlgList, Config},
    error::SshResult,
    model::{Packet, SecPacket},
};

enum SessionState<S>
where
    S: Read + Write,
{
    Init(Config, S),
    Version(Config, S),
    Auth(Client, S),
    Connected(Client, S),
}

pub struct SessionConnector<S>
where
    S: Read + Write,
{
    inner: SessionState<S>,
}

impl<S> SessionConnector<S>
where
    S: Read + Write,
{
    fn connect(self) -> SshResult<Self> {
        match self.inner {
            SessionState::Init(config, stream) => Self {
                inner: SessionState::Version(config, stream),
            }
            .connect(),
            SessionState::Version(mut config, mut stream) => {
                info!("start for version negotiation.");
                // Send Client version
                config.ver.send_our_version(&mut stream)?;

                // Receive the server version
                config
                    .ver
                    .read_server_version(&mut stream, config.timeout)?;
                // Version validate
                config.ver.validate()?;

                // from now on
                // each step of the interaction is subject to the ssh constraints on the packet
                // so we create a client to hide the underlay details
                let client = Client::new(config);

                Self {
                    inner: SessionState::Auth(client, stream),
                }
                .connect()
            }
            SessionState::Auth(mut client, mut stream) => {
                // before auth,
                // we should have a key exchange at first
                let mut digest = Digest::new();
                let server_algs = SecPacket::from_stream(&mut stream, &mut client)?;
                digest.hash_ctx.set_i_s(server_algs.get_inner());
                let server_algs = AlgList::unpack(server_algs)?;
                client.key_agreement(&mut stream, server_algs, &mut digest)?;
                client.do_auth(&mut stream, &digest)?;
                Ok(Self {
                    inner: SessionState::Connected(client, stream),
                })
            }
            _ => unreachable!(),
        }
    }

    /// To run this ssh session on the local thread
    ///
    /// It will return a [LocalSession] which doesn't support multithread concurrency
    ///
    pub fn run_local(self) -> LocalSession<S> {
        if let SessionState::Connected(client, stream) = self.inner {
            LocalSession::new(client, stream)
        } else {
            unreachable!("Why you here?")
        }
    }

    /// close the session and consume it
    ///
    pub fn close(self) {
        drop(self)
    }
}

impl<S> SessionConnector<S>
where
    S: Read + Write + Send + 'static,
{
    /// To spwan a new thread to run this ssh session
    ///
    /// It will return a [SessionBroker] which supports multithread concurrency
    ///
    pub fn run_backend(self) -> SessionBroker {
        if let SessionState::Connected(client, stream) = self.inner {
            SessionBroker::new(client, stream)
        } else {
            unreachable!("Why you here?")
        }
    }
}

#[derive(Default)]
pub struct SessionBuilder {
    config: Config,
}

impl SessionBuilder {
    pub fn new() -> Self {
        Self {
            ..Default::default()
        }
    }

    pub fn disable_default() -> Self {
        Self {
            config: Config::disable_default(),
        }
    }

    /// Read/Write timeout for local SSH mode. Use None to disable timeout.
    /// This is a global timeout only take effect after the session is established
    ///
    /// Use `connect_with_timeout` instead if you want to add timeout
    /// when connect to the target SSH server
    pub fn timeout(mut self, timeout: Option<Duration>) -> Self {
        self.config.timeout = timeout;
        self
    }

    pub fn username(mut self, username: &str) -> Self {
        self.config.auth.username(username).unwrap();
        self
    }

    pub fn password(mut self, password: &str) -> Self {
        self.config.auth.password(password).unwrap();
        self
    }

    pub fn private_key<K>(mut self, private_key: K) -> Self
    where
        K: ToString,
    {
        match self.config.auth.private_key(private_key) {
            Ok(_) => (),
            Err(e) => error!(
                "Parse private key from string: {}, will fallback to password authentication",
                e
            ),
        }
        self
    }

    pub fn private_key_path<P>(mut self, key_path: P) -> Self
    where
        P: AsRef<Path>,
    {
        match self.config.auth.private_key_path(key_path) {
            Ok(_) => (),
            Err(e) => error!(
                "Parse private key from file: {}, will fallback to password authentication",
                e
            ),
        }
        self
    }

    pub fn add_kex_algorithms(mut self, alg: Kex) -> Self {
        self.config.algs.key_exchange.push(alg);
        self
    }

    pub fn del_kex_algorithms(mut self, alg: Kex) -> Self {
        self.config.algs.key_exchange.retain(|x| *x != alg);
        self
    }

    pub fn add_pubkey_algorithms(mut self, alg: PubKey) -> Self {
        self.config.algs.public_key.push(alg);
        self
    }

    pub fn del_pubkey_algorithms(mut self, alg: PubKey) -> Self {
        self.config.algs.public_key.retain(|x| *x != alg);
        self
    }

    pub fn add_enc_algorithms(mut self, alg: Enc) -> Self {
        self.config.algs.c_encryption.push(alg);
        self.config.algs.s_encryption.push(alg);
        self
    }

    pub fn del_enc_algorithms(mut self, alg: Enc) -> Self {
        self.config.algs.c_encryption.retain(|x| *x != alg);
        self.config.algs.s_encryption.retain(|x| *x != alg);
        self
    }

    pub fn add_mac_algortihms(mut self, alg: Mac) -> Self {
        self.config.algs.c_mac.push(alg);
        self.config.algs.s_mac.push(alg);
        self
    }

    pub fn del_mac_algortihms(mut self, alg: Mac) -> Self {
        self.config.algs.c_mac.retain(|x| *x != alg);
        self.config.algs.s_mac.retain(|x| *x != alg);
        self
    }

    pub fn add_compress_algorithms(mut self, alg: Compress) -> Self {
        self.config.algs.c_compress.push(alg);
        self.config.algs.s_compress.push(alg);
        self
    }

    pub fn del_compress_algorithms(mut self, alg: Compress) -> Self {
        self.config.algs.c_compress.retain(|x| *x != alg);
        self.config.algs.s_compress.retain(|x| *x != alg);
        self
    }

    /// Create a TCP connection to the target server
    ///
    pub fn connect<A>(self, addr: A) -> SshResult<SessionConnector<TcpStream>>
    where
        A: ToSocketAddrs,
    {
        // connect tcp by default
        let tcp = if let Some(ref to) = self.config.timeout {
            TcpStream::connect_timeout(&addr.to_socket_addrs()?.next().unwrap(), *to)?
        } else {
            TcpStream::connect(addr)?
        };

        // default nonblocking
        tcp.set_nonblocking(true).unwrap();
        self.connect_bio(tcp)
    }

    /// Create a TCP connection to the target server, with timeout provided
    ///
    pub fn connect_with_timeout<A>(
        self,
        addr: A,
        timeout: Option<Duration>,
    ) -> SshResult<SessionConnector<TcpStream>>
    where
        A: ToSocketAddrs,
    {
        // connect tcp with custom connection timeout
        let tcp = if let Some(ref to) = timeout {
            TcpStream::connect_timeout(&addr.to_socket_addrs()?.next().unwrap(), *to)?
        } else {
            TcpStream::connect(addr)?
        };

        // default nonblocking
        tcp.set_nonblocking(true).unwrap();
        self.connect_bio(tcp)
    }

    /// connect to target server w/ a bio object
    ///
    /// which requires to implement `std::io::{Read, Write}`
    ///
    pub fn connect_bio<S>(mut self, stream: S) -> SshResult<SessionConnector<S>>
    where
        S: Read + Write,
    {
        self.config.tune_alglist_on_private_key();
        SessionConnector {
            inner: SessionState::Init(self.config, stream),
        }
        .connect()
    }
}