bssh 1.2.1

Parallel SSH command execution tool for cluster management
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// Copyright 2025 Lablup Inc. and Jeongkyu Shin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! SSH connection options parsing
//!
//! Handles connection-related configuration options including keepalive
//! settings, timeouts, compression, and network settings.

use crate::ssh::ssh_config::parser::helpers::parse_yes_no;
use crate::ssh::ssh_config::types::SshHostConfig;
use anyhow::{Context, Result};

/// Parse connection-related SSH configuration options
pub(super) fn parse_connection_option(
    host: &mut SshHostConfig,
    keyword: &str,
    args: &[String],
    line_number: usize,
) -> Result<()> {
    match keyword {
        "serveraliveinterval" => {
            if args.is_empty() {
                anyhow::bail!("ServerAliveInterval requires a value at line {line_number}");
            }
            let interval: u32 = args[0].parse().with_context(|| {
                format!(
                    "Invalid ServerAliveInterval value '{}' at line {}",
                    args[0], line_number
                )
            })?;
            host.server_alive_interval = Some(interval);
        }
        "serveralivecountmax" => {
            if args.is_empty() {
                anyhow::bail!("ServerAliveCountMax requires a value at line {line_number}");
            }
            let count: u32 = args[0].parse().with_context(|| {
                format!(
                    "Invalid ServerAliveCountMax value '{}' at line {}",
                    args[0], line_number
                )
            })?;
            host.server_alive_count_max = Some(count);
        }
        "connecttimeout" => {
            if args.is_empty() {
                anyhow::bail!("ConnectTimeout requires a value at line {line_number}");
            }
            let timeout: u32 = args[0].parse().with_context(|| {
                format!(
                    "Invalid ConnectTimeout value '{}' at line {}",
                    args[0], line_number
                )
            })?;
            host.connect_timeout = Some(timeout);
        }
        "connectionattempts" => {
            if args.is_empty() {
                anyhow::bail!("ConnectionAttempts requires a value at line {line_number}");
            }
            let attempts: u32 = args[0].parse().with_context(|| {
                format!(
                    "Invalid ConnectionAttempts value '{}' at line {}",
                    args[0], line_number
                )
            })?;
            host.connection_attempts = Some(attempts);
        }
        "batchmode" => {
            if args.is_empty() {
                anyhow::bail!("BatchMode requires a value at line {line_number}");
            }
            host.batch_mode = Some(parse_yes_no(&args[0], line_number)?);
        }
        "compression" => {
            if args.is_empty() {
                anyhow::bail!("Compression requires a value at line {line_number}");
            }
            host.compression = Some(parse_yes_no(&args[0], line_number)?);
        }
        "tcpkeepalive" => {
            if args.is_empty() {
                anyhow::bail!("TCPKeepAlive requires a value at line {line_number}");
            }
            host.tcp_keep_alive = Some(parse_yes_no(&args[0], line_number)?);
        }
        "addressfamily" => {
            if args.is_empty() {
                anyhow::bail!("AddressFamily requires a value at line {line_number}");
            }
            host.address_family = Some(args[0].clone());
        }
        "bindaddress" => {
            if args.is_empty() {
                anyhow::bail!("BindAddress requires a value at line {line_number}");
            }
            host.bind_address = Some(args[0].clone());
        }
        "bindinterface" => {
            if args.is_empty() {
                anyhow::bail!("BindInterface requires a value at line {line_number}");
            }
            // Security: Validate network interface name to prevent injection attacks
            let interface = &args[0];
            if interface.is_empty() {
                anyhow::bail!("BindInterface cannot be empty at line {line_number}");
            }
            // Network interface names on Linux/macOS are typically:
            // - eth0, eth1, etc. (Linux)
            // - en0, en1, etc. (macOS)
            // - lo, lo0 (loopback)
            // - wlan0, wlp3s0, etc. (wireless)
            // - docker0, br0, tun0, tap0, etc. (virtual interfaces)
            // - bond0, team0, etc. (bonded interfaces)
            // - vlan interfaces like eth0.100
            // Maximum length is typically 15 characters on Linux (IFNAMSIZ - 1)
            if interface.len() > 15 {
                anyhow::bail!(
                    "BindInterface '{interface}' at line {line_number} exceeds maximum interface name length of 15 characters"
                );
            }

            // Only allow alphanumeric, dots, hyphens, underscores, and colons (for aliases like eth0:1)
            if !interface
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_' || c == ':')
            {
                anyhow::bail!(
                    "BindInterface '{interface}' at line {line_number} contains invalid characters. \
                     Network interface names can only contain alphanumeric characters, dots, hyphens, underscores, and colons"
                );
            }

            // Additional validation: interface name shouldn't start with a dot or hyphen
            if interface.starts_with('.') || interface.starts_with('-') {
                anyhow::bail!(
                    "BindInterface '{interface}' at line {line_number} cannot start with a dot or hyphen"
                );
            }

            // Prevent potential path traversal or command injection
            if interface.contains("..") || interface.contains("/") || interface.contains("\\") {
                anyhow::bail!(
                    "BindInterface '{interface}' at line {line_number} contains dangerous characters that could be used for injection attacks"
                );
            }

            host.bind_interface = Some(interface.clone());
        }
        "ipqos" => {
            if args.is_empty() {
                anyhow::bail!("IPQoS requires a value at line {line_number}");
            }
            // IPQoS can have one or two values (interactive and bulk)
            // Valid values are: af11-af43, cs0-cs7, ef, lowdelay, throughput, reliability, or numeric (0-63 for DSCP, 0-255 for ToS)
            if args.len() > 2 {
                anyhow::bail!(
                    "IPQoS at line {} accepts at most 2 values (interactive and bulk), got {}",
                    line_number,
                    args.len()
                );
            }

            // Validate each QoS value
            let valid_qos_values = [
                "af11",
                "af12",
                "af13",
                "af21",
                "af22",
                "af23",
                "af31",
                "af32",
                "af33",
                "af41",
                "af42",
                "af43",
                "cs0",
                "cs1",
                "cs2",
                "cs3",
                "cs4",
                "cs5",
                "cs6",
                "cs7",
                "ef",
                "lowdelay",
                "throughput",
                "reliability",
                "none",
            ];

            // Additional mappings for common aliases
            let qos_aliases = [
                ("expedited", "ef"),
                ("assured", "af11"),
                ("besteffort", "cs0"),
                ("background", "cs1"),
            ];

            for value in args {
                // Check if it's a known QoS value or alias
                let lower_value = value.to_lowercase();
                let normalized = qos_aliases
                    .iter()
                    .find(|(alias, _)| *alias == lower_value.as_str())
                    .map(|(_, canonical)| *canonical)
                    .unwrap_or(lower_value.as_str());

                if !valid_qos_values.contains(&normalized) {
                    // Check if it's a numeric value
                    match value.parse::<u8>() {
                        Ok(num) => {
                            // DSCP values are 0-63 (6 bits)
                            // ToS values are 0-255 (8 bits) but only certain values are valid
                            if num > 63 {
                                // If it's a ToS value (0-255), check if it's a valid one
                                // Valid ToS values: 0x10 (lowdelay), 0x08 (throughput), 0x04 (reliability)
                                let valid_tos = [0x00, 0x04, 0x08, 0x10, 0xff];
                                if !valid_tos.contains(&num) {
                                    tracing::warn!(
                                        "IPQoS value '{}' ({:#04x}) at line {} is not a standard DSCP (0-63) or ToS value",
                                        value, num, line_number
                                    );
                                }
                            }
                        }
                        Err(_) => {
                            // Check for hex notation (0x prefix)
                            if value.starts_with("0x") || value.starts_with("0X") {
                                if let Ok(num) = u8::from_str_radix(&value[2..], 16) {
                                    if num > 63 && ![0x00, 0x04, 0x08, 0x10, 0xff].contains(&num) {
                                        tracing::warn!(
                                            "IPQoS hex value '{}' at line {} is outside standard ranges",
                                            value, line_number
                                        );
                                    }
                                } else {
                                    anyhow::bail!(
                                        "IPQoS value '{value}' at line {line_number} is not a valid hexadecimal number"
                                    );
                                }
                            } else {
                                anyhow::bail!(
                                    "IPQoS value '{value}' at line {line_number} is not valid. \
                                     Valid values are: af11-af43, cs0-cs7, ef, lowdelay, throughput, \
                                     reliability, none, or numeric (0-63 for DSCP, specific ToS values)"
                                );
                            }
                        }
                    }
                }
            }

            // Limit total length to prevent memory exhaustion
            let combined = args.join(" ");
            if combined.len() > 100 {
                anyhow::bail!("IPQoS value at line {line_number} is too long (max 100 characters)");
            }

            host.ipqos = Some(combined);
        }
        "rekeylimit" => {
            if args.is_empty() {
                anyhow::bail!("RekeyLimit requires a value at line {line_number}");
            }
            // RekeyLimit can have one or two values (data limit and time limit)
            // Format: <data> [<time>]
            // Data: default, none, or number with optional suffix (K/M/G/T)
            // Time: none or number with optional suffix (s/m/h/d/w)

            if args.len() > 2 {
                anyhow::bail!(
                    "RekeyLimit at line {} accepts at most 2 values (data and time), got {}",
                    line_number,
                    args.len()
                );
            }

            // Validate data limit (first argument)
            let data_limit = &args[0];
            if data_limit != "default" && data_limit != "none" {
                // Parse size with optional suffix
                let (number_part, _suffix, multiplier) =
                    if let Some(stripped) = data_limit.strip_suffix(&['K', 'k'][..]) {
                        (stripped, "K", 1024u64)
                    } else if let Some(stripped) = data_limit.strip_suffix(&['M', 'm'][..]) {
                        (stripped, "M", 1024u64 * 1024)
                    } else if let Some(stripped) = data_limit.strip_suffix(&['G', 'g'][..]) {
                        (stripped, "G", 1024u64 * 1024 * 1024)
                    } else if let Some(stripped) = data_limit.strip_suffix(&['T', 't'][..]) {
                        (stripped, "T", 1024u64 * 1024 * 1024 * 1024)
                    } else {
                        // Plain number (bytes)
                        (data_limit.as_str(), "", 1u64)
                    };

                match number_part.parse::<u64>() {
                    Ok(num) => {
                        // Check for overflow when applying multiplier
                        if let Some(total) = num.checked_mul(multiplier) {
                            // Warn if rekey limit is very large (> 1TB)
                            if total > 1024u64 * 1024 * 1024 * 1024 {
                                tracing::warn!(
                                    "RekeyLimit data limit '{}' at line {} is very large ({}TB). \
                                     This may not be effective for security",
                                    data_limit,
                                    line_number,
                                    total / (1024u64 * 1024 * 1024 * 1024)
                                );
                            }
                            // Warn if rekey limit is very small (< 1KB)
                            if total < 1024 && total != 0 {
                                tracing::warn!(
                                    "RekeyLimit data limit '{}' at line {} is very small ({} bytes). \
                                     This may cause frequent rekeying",
                                    data_limit, line_number, total
                                );
                            }
                        } else {
                            anyhow::bail!(
                                "RekeyLimit data limit '{data_limit}' at line {line_number} would overflow. \
                                 Please use a smaller value"
                            );
                        }
                    }
                    Err(_) => {
                        anyhow::bail!(
                            "RekeyLimit data limit '{data_limit}' at line {line_number} is invalid. \
                             Use 'default', 'none', or a number with optional suffix (K/M/G/T)"
                        );
                    }
                }

                // Prevent absurdly long input strings
                if data_limit.len() > 20 {
                    anyhow::bail!(
                        "RekeyLimit data limit at line {line_number} is too long (max 20 characters)"
                    );
                }
            }

            // Validate time limit (second argument, if present)
            if args.len() > 1 {
                let time_limit = &args[1];
                if time_limit != "none" {
                    // Parse time with optional suffix
                    let (number_part, _suffix, multiplier) =
                        if let Some(stripped) = time_limit.strip_suffix(&['s', 'S'][..]) {
                            (stripped, "s", 1u64)
                        } else if let Some(stripped) = time_limit.strip_suffix(&['m', 'M'][..]) {
                            (stripped, "m", 60u64)
                        } else if let Some(stripped) = time_limit.strip_suffix(&['h', 'H'][..]) {
                            (stripped, "h", 3600u64)
                        } else if let Some(stripped) = time_limit.strip_suffix(&['d', 'D'][..]) {
                            (stripped, "d", 86400u64)
                        } else if let Some(stripped) = time_limit.strip_suffix(&['w', 'W'][..]) {
                            (stripped, "w", 604800u64)
                        } else {
                            // Plain number (seconds)
                            (time_limit.as_str(), "", 1u64)
                        };

                    match number_part.parse::<u64>() {
                        Ok(num) => {
                            // Check for overflow when applying multiplier
                            if let Some(total_seconds) = num.checked_mul(multiplier) {
                                // Warn if rekey time is very long (> 1 week)
                                if total_seconds > 604800 {
                                    tracing::warn!(
                                        "RekeyLimit time limit '{}' at line {} is very long ({} days). \
                                         This may reduce security",
                                        time_limit, line_number, total_seconds / 86400
                                    );
                                }
                                // Warn if rekey time is very short (< 60 seconds)
                                if total_seconds < 60 && total_seconds != 0 {
                                    tracing::warn!(
                                        "RekeyLimit time limit '{}' at line {} is very short ({} seconds). \
                                         This may cause frequent rekeying",
                                        time_limit, line_number, total_seconds
                                    );
                                }
                            } else {
                                anyhow::bail!(
                                    "RekeyLimit time limit '{time_limit}' at line {line_number} would overflow. \
                                     Please use a smaller value"
                                );
                            }
                        }
                        Err(_) => {
                            anyhow::bail!(
                                "RekeyLimit time limit '{time_limit}' at line {line_number} is invalid. \
                                 Use 'none' or a number with optional suffix (s/m/h/d/w)"
                            );
                        }
                    }

                    // Prevent absurdly long input strings
                    if time_limit.len() > 20 {
                        anyhow::bail!(
                            "RekeyLimit time limit at line {line_number} is too long (max 20 characters)"
                        );
                    }
                }
            }

            // Limit total length to prevent memory exhaustion
            let combined = args.join(" ");
            if combined.len() > 50 {
                anyhow::bail!(
                    "RekeyLimit value at line {line_number} is too long (max 50 characters total)"
                );
            }

            host.rekey_limit = Some(combined);
        }
        _ => unreachable!("Unexpected keyword in parse_connection_option: {}", keyword),
    }

    Ok(())
}