russh-extra-core 0.1.2

Core types shared by russh-extra crates.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Client and server configuration.

use std::time::Duration;

use crate::{Credential, Endpoint, Error, HostKeyErrorKind, Identity, Result, Username};

/// Host-key verification policy.
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub enum HostKeyPolicy {
    /// Reject host keys unless a future persistent store or verifier accepts
    /// them. This is the default.
    #[default]
    Strict,
    /// Accept every host key.
    ///
    /// **Insecure**: this disables host-key verification entirely. Only use
    /// this policy in tests or controlled environments.
    InsecureAcceptAny,
    /// Accept only pinned SHA256 host-key fingerprints.
    PinnedSha256(Vec<HostKeyFingerprint>),
}

impl HostKeyPolicy {
    /// Creates a pinned SHA256 host-key policy.
    pub fn pinned_sha256(fingerprint: impl Into<String>) -> Result<Self> {
        Ok(Self::PinnedSha256(vec![HostKeyFingerprint::sha256(
            fingerprint,
        )?]))
    }

    /// Returns whether this policy accepts any host key.
    pub fn accepts_any(&self) -> bool {
        matches!(self, Self::InsecureAcceptAny)
    }
}

/// Pinned host-key fingerprint.
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct HostKeyFingerprint {
    algorithm: HostKeyFingerprintAlgorithm,
    value: String,
}

impl HostKeyFingerprint {
    /// Creates a SHA256 host-key fingerprint.
    pub fn sha256(value: impl Into<String>) -> Result<Self> {
        let value = value.into();
        validate_sha256_fingerprint(&value)?;
        Ok(Self {
            algorithm: HostKeyFingerprintAlgorithm::Sha256,
            value,
        })
    }

    /// Returns the fingerprint algorithm.
    pub fn algorithm(&self) -> HostKeyFingerprintAlgorithm {
        self.algorithm
    }

    /// Returns the fingerprint value.
    pub fn value(&self) -> &str {
        &self.value
    }
}

/// Host-key fingerprint algorithm.
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum HostKeyFingerprintAlgorithm {
    /// OpenSSH-style SHA256 host-key fingerprint.
    Sha256,
}

/// Client connection configuration.
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ClientConfig {
    endpoint: Endpoint,
    username: Option<Username>,
    #[cfg_attr(feature = "serde", serde(skip))]
    credentials: Vec<Credential>,
    timeouts: Timeouts,
    keepalive: Keepalive,
    host_key_policy: HostKeyPolicy,
}

impl ClientConfig {
    /// Creates a config for the given endpoint.
    pub fn new(endpoint: impl Into<Endpoint>) -> Self {
        Self {
            endpoint: endpoint.into(),
            username: None,
            credentials: Vec::new(),
            timeouts: Timeouts::default(),
            keepalive: Keepalive::default(),
            host_key_policy: HostKeyPolicy::default(),
        }
    }

    /// Returns the configured endpoint.
    pub fn endpoint(&self) -> &Endpoint {
        &self.endpoint
    }

    /// Sets the endpoint.
    pub fn set_endpoint(&mut self, endpoint: impl Into<Endpoint>) {
        self.endpoint = endpoint.into();
    }

    /// Returns the optional username.
    pub fn username(&self) -> Option<&Username> {
        self.username.as_ref()
    }

    /// Sets the username.
    pub fn set_username(&mut self, username: impl Into<Username>) {
        self.username = Some(username.into());
    }

    /// Returns configured credentials in preference order.
    pub fn credentials(&self) -> &[Credential] {
        &self.credentials
    }

    /// Adds a credential.
    pub fn add_credential(&mut self, credential: Credential) {
        self.credentials.push(credential);
    }

    /// Adds an SSH agent credential.
    pub fn use_agent(&mut self) {
        self.add_credential(Credential::identity(Identity::agent()));
    }

    /// Returns timeout settings.
    pub fn timeouts(&self) -> &Timeouts {
        &self.timeouts
    }

    /// Sets timeout settings.
    pub fn set_timeouts(&mut self, timeouts: Timeouts) {
        self.timeouts = timeouts;
    }

    /// Returns keepalive settings.
    pub fn keepalive(&self) -> &Keepalive {
        &self.keepalive
    }

    /// Sets keepalive settings.
    pub fn set_keepalive(&mut self, keepalive: Keepalive) {
        self.keepalive = keepalive;
    }

    /// Returns whether strict host key checking is enabled.
    pub fn strict_host_key_checking(&self) -> bool {
        !self.host_key_policy.accepts_any()
    }

    /// Sets strict host key checking.
    #[deprecated = "use set_host_key_policy instead"]
    pub fn set_strict_host_key_checking(&mut self, enabled: bool) {
        self.host_key_policy = if enabled {
            HostKeyPolicy::Strict
        } else {
            HostKeyPolicy::InsecureAcceptAny
        };
    }

    /// Returns the configured host-key policy.
    pub fn host_key_policy(&self) -> &HostKeyPolicy {
        &self.host_key_policy
    }

    /// Sets the host-key policy.
    pub fn set_host_key_policy(&mut self, policy: HostKeyPolicy) {
        self.host_key_policy = policy;
    }
}

impl Default for ClientConfig {
    fn default() -> Self {
        Self::new(Endpoint::default())
    }
}

/// Server configuration.
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ServerConfig {
    listen: Endpoint,
    server_id: String,
    max_sessions: usize,
}

impl ServerConfig {
    /// Creates server configuration for a listen endpoint.
    pub fn new(listen: impl Into<Endpoint>) -> Self {
        Self {
            listen: listen.into(),
            server_id: "SSH-2.0-russh-extra".to_owned(),
            max_sessions: 1024,
        }
    }

    /// Returns the listen endpoint.
    pub fn listen(&self) -> &Endpoint {
        &self.listen
    }

    /// Sets the listen endpoint.
    pub fn set_listen(&mut self, listen: impl Into<Endpoint>) {
        self.listen = listen.into();
    }

    /// Returns the SSH identification string.
    pub fn server_id(&self) -> &str {
        &self.server_id
    }

    /// Sets the SSH identification string.
    pub fn set_server_id(&mut self, server_id: impl Into<String>) {
        self.server_id = server_id.into();
    }

    /// Returns the configured maximum session count.
    pub fn max_sessions(&self) -> usize {
        self.max_sessions
    }

    /// Sets the maximum session count.
    pub fn set_max_sessions(&mut self, max_sessions: usize) {
        self.max_sessions = max_sessions;
    }
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self::new(("127.0.0.1", 0))
    }
}

/// Timeout configuration.
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Timeouts {
    /// Timeout for establishing a TCP connection.
    pub connect: Duration,
    /// Timeout for completing authentication.
    pub auth: Duration,
    /// Timeout for opening a channel.
    pub channel_open: Duration,
}

impl Default for Timeouts {
    fn default() -> Self {
        Self {
            connect: Duration::from_secs(30),
            auth: Duration::from_secs(30),
            channel_open: Duration::from_secs(10),
        }
    }
}

impl Timeouts {
    /// Creates new timeout configuration.
    pub fn new(connect: Duration, auth: Duration, channel_open: Duration) -> Self {
        Self {
            connect,
            auth,
            channel_open,
        }
    }
}

/// Keepalive configuration.
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Keepalive {
    /// Whether keepalives are enabled.
    pub enabled: bool,
    /// Interval between keepalive messages.
    pub interval: Duration,
    /// Number of unanswered keepalives before disconnecting.
    pub max_missed: u32,
}

impl Default for Keepalive {
    fn default() -> Self {
        Self {
            enabled: true,
            interval: Duration::from_secs(30),
            max_missed: 3,
        }
    }
}

fn validate_sha256_fingerprint(value: &str) -> Result<()> {
    let Some(rest) = value.strip_prefix("SHA256:") else {
        return Err(Error::host_key(
            HostKeyErrorKind::Unsupported,
            "host-key fingerprint must start with SHA256:",
        ));
    };

    if rest.is_empty() {
        return Err(Error::host_key(
            HostKeyErrorKind::Unavailable,
            "host-key fingerprint must not be empty",
        ));
    }

    if rest.bytes().any(|byte| byte.is_ascii_whitespace()) {
        return Err(Error::host_key(
            HostKeyErrorKind::Rejected,
            "host-key fingerprint must not contain whitespace",
        ));
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use crate::{
        ClientConfig, Endpoint, Error, HostKeyFingerprint, HostKeyFingerprintAlgorithm,
        HostKeyPolicy,
    };

    #[test]
    fn server_config_defaults_to_loopback_ephemeral_port() {
        let config = crate::ServerConfig::default();

        assert_eq!(config.listen(), &Endpoint::new("127.0.0.1", 0));
    }

    #[test]
    fn client_config_defaults_to_strict_host_key_policy() {
        let config = ClientConfig::default();

        assert_eq!(config.host_key_policy(), &HostKeyPolicy::Strict);
        assert!(config.strict_host_key_checking());
    }

    #[test]
    #[allow(deprecated)]
    fn disabling_strict_host_key_checking_sets_accept_any_policy() {
        let mut config = ClientConfig::default();

        config.set_strict_host_key_checking(false);

        assert_eq!(config.host_key_policy(), &HostKeyPolicy::InsecureAcceptAny);
        assert!(!config.strict_host_key_checking());
    }

    #[test]
    fn validates_sha256_host_key_fingerprints() {
        let fingerprint = HostKeyFingerprint::sha256("SHA256:abc123+/=").unwrap();

        assert_eq!(fingerprint.algorithm(), HostKeyFingerprintAlgorithm::Sha256);
        assert_eq!(fingerprint.value(), "SHA256:abc123+/=");
    }

    #[test]
    fn rejects_invalid_sha256_host_key_fingerprints() {
        let error = HostKeyFingerprint::sha256("MD5:abc").unwrap_err();
        assert!(matches!(error, Error::HostKey(_)));

        let error = HostKeyFingerprint::sha256("SHA256:").unwrap_err();
        assert!(matches!(error, Error::HostKey(_)));
    }

    #[test]
    #[cfg(feature = "serde")]
    fn client_config_serialization_skips_credentials() {
        let mut config = ClientConfig::new(Endpoint::new("example.com", 2222));
        config.add_credential(crate::Credential::password("secret"));

        let serialized = serde_json::to_string(&config).unwrap();
        let deserialized: ClientConfig = serde_json::from_str(&serialized).unwrap();

        assert!(!serialized.contains("secret"));
        assert!(!serialized.contains("credentials"));
        assert!(deserialized.credentials().is_empty());
    }

    #[test]
    fn client_config_debug_does_not_expose_credential_content() {
        let mut config = ClientConfig::new(Endpoint::new("example.com", 2222));
        config.add_credential(crate::Credential::password("my-secret-password"));
        let debug = format!("{:?}", config);
        assert!(!debug.contains("my-secret-password"));
        assert!(debug.contains("Password(***)"));
    }
}