bssh 1.0.0

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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
// 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 security options parsing
//!
//! Handles security-related configuration options including host key
//! verification, known hosts files, and cryptographic algorithms.

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

/// Parse security-related SSH configuration options
pub(super) fn parse_security_option(
    host: &mut SshHostConfig,
    keyword: &str,
    args: &[String],
    line_number: usize,
) -> Result<()> {
    match keyword {
        "stricthostkeychecking" => {
            if args.is_empty() {
                anyhow::bail!("StrictHostKeyChecking requires a value at line {line_number}");
            }
            let value = &args[0];
            tracing::debug!(
                "Setting StrictHostKeyChecking to '{}' at line {} (security-sensitive)",
                value,
                line_number
            );
            host.strict_host_key_checking = Some(value.clone());
        }
        "userknownhostsfile" => {
            if args.is_empty() {
                anyhow::bail!("UserKnownHostsFile requires a value at line {line_number}");
            }
            let path =
                secure_validate_path(&args[0], "known_hosts", line_number).with_context(|| {
                    format!("Invalid UserKnownHostsFile path at line {line_number}")
                })?;
            host.user_known_hosts_file = Some(path);
        }
        "globalknownhostsfile" => {
            if args.is_empty() {
                anyhow::bail!("GlobalKnownHostsFile requires a value at line {line_number}");
            }
            let path =
                secure_validate_path(&args[0], "known_hosts", line_number).with_context(|| {
                    format!("Invalid GlobalKnownHostsFile path at line {line_number}")
                })?;
            host.global_known_hosts_file = Some(path);
        }
        "hostkeyalgorithms" => {
            if args.is_empty() {
                anyhow::bail!("HostKeyAlgorithms requires a value at line {line_number}");
            }
            const MAX_ALGORITHMS: usize = 50;
            const MAX_ALGORITHM_NAME_LENGTH: usize = 256;

            let mut algorithms = Vec::with_capacity(MAX_ALGORITHMS.min(args.len() * 2));
            let mut total_count = 0;
            let mut truncated = false;

            for arg in args {
                for algorithm in arg.split(',') {
                    total_count += 1;

                    if algorithms.len() >= MAX_ALGORITHMS {
                        truncated = true;
                        break;
                    }

                    let trimmed = algorithm.trim();
                    if trimmed.is_empty() {
                        continue;
                    }

                    if trimmed.len() > MAX_ALGORITHM_NAME_LENGTH {
                        tracing::warn!(
                            "HostKeyAlgorithm name at line {} exceeds maximum length of {} characters, skipping",
                            line_number, MAX_ALGORITHM_NAME_LENGTH
                        );
                        continue;
                    }

                    // Security: Validate algorithm name contains only safe characters
                    if !trimmed.chars().all(|c| {
                        c.is_ascii_alphanumeric()
                            || c == '-'
                            || c == '.'
                            || c == '_'
                            || c == '@'
                            || c == '+'
                    }) {
                        anyhow::bail!(
                            "HostKeyAlgorithms at line {} contains invalid characters in algorithm name '{}'. \
                             Only alphanumeric characters, hyphens, dots, underscores, @ and + are allowed",
                            line_number, trimmed
                        );
                    }

                    algorithms.push(trimmed.to_string());
                }
                if truncated {
                    break;
                }
            }

            if truncated {
                tracing::warn!(
                    "HostKeyAlgorithms at line {} contains {} algorithms, truncated to first {}",
                    line_number,
                    total_count,
                    MAX_ALGORITHMS
                );
            }

            if algorithms.is_empty() {
                anyhow::bail!(
                    "HostKeyAlgorithms at line {} must contain at least one valid algorithm",
                    line_number
                );
            }

            host.host_key_algorithms = algorithms;
        }
        "kexalgorithms" => {
            if args.is_empty() {
                anyhow::bail!("KexAlgorithms requires a value at line {line_number}");
            }
            const MAX_ALGORITHMS: usize = 50;
            const MAX_ALGORITHM_NAME_LENGTH: usize = 256;

            let mut algorithms = Vec::with_capacity(MAX_ALGORITHMS.min(args.len() * 2));
            let mut total_count = 0;
            let mut truncated = false;

            for arg in args {
                for algorithm in arg.split(',') {
                    total_count += 1;

                    if algorithms.len() >= MAX_ALGORITHMS {
                        truncated = true;
                        break;
                    }

                    let trimmed = algorithm.trim();
                    if trimmed.is_empty() {
                        continue;
                    }

                    if trimmed.len() > MAX_ALGORITHM_NAME_LENGTH {
                        tracing::warn!(
                            "KexAlgorithm name at line {} exceeds maximum length of {} characters, skipping",
                            line_number, MAX_ALGORITHM_NAME_LENGTH
                        );
                        continue;
                    }

                    // Security: Validate algorithm name contains only safe characters
                    if !trimmed.chars().all(|c| {
                        c.is_ascii_alphanumeric()
                            || c == '-'
                            || c == '.'
                            || c == '_'
                            || c == '@'
                            || c == '+'
                    }) {
                        anyhow::bail!(
                            "KexAlgorithms at line {} contains invalid characters in algorithm name '{}'. \
                             Only alphanumeric characters, hyphens, dots, underscores, @ and + are allowed",
                            line_number, trimmed
                        );
                    }

                    algorithms.push(trimmed.to_string());
                }
                if truncated {
                    break;
                }
            }

            if truncated {
                tracing::warn!(
                    "KexAlgorithms at line {} contains {} algorithms, truncated to first {}",
                    line_number,
                    total_count,
                    MAX_ALGORITHMS
                );
            }

            if algorithms.is_empty() {
                anyhow::bail!(
                    "KexAlgorithms at line {} must contain at least one valid algorithm",
                    line_number
                );
            }

            host.kex_algorithms = algorithms;
        }
        "ciphers" => {
            if args.is_empty() {
                anyhow::bail!("Ciphers requires a value at line {line_number}");
            }
            const MAX_CIPHERS: usize = 50;
            const MAX_CIPHER_NAME_LENGTH: usize = 256;

            let mut ciphers = Vec::with_capacity(MAX_CIPHERS.min(args.len() * 2));
            let mut total_count = 0;
            let mut truncated = false;

            for arg in args {
                for cipher in arg.split(',') {
                    total_count += 1;

                    if ciphers.len() >= MAX_CIPHERS {
                        truncated = true;
                        break;
                    }

                    let trimmed = cipher.trim();
                    if trimmed.is_empty() {
                        continue;
                    }

                    if trimmed.len() > MAX_CIPHER_NAME_LENGTH {
                        tracing::warn!(
                            "Cipher name at line {} exceeds maximum length of {} characters, skipping",
                            line_number, MAX_CIPHER_NAME_LENGTH
                        );
                        continue;
                    }

                    // Security: Validate cipher name contains only safe characters
                    if !trimmed.chars().all(|c| {
                        c.is_ascii_alphanumeric()
                            || c == '-'
                            || c == '.'
                            || c == '_'
                            || c == '@'
                            || c == '+'
                    }) {
                        anyhow::bail!(
                            "Ciphers at line {} contains invalid characters in cipher name '{}'. \
                             Only alphanumeric characters, hyphens, dots, underscores, @ and + are allowed",
                            line_number, trimmed
                        );
                    }

                    ciphers.push(trimmed.to_string());
                }
                if truncated {
                    break;
                }
            }

            if truncated {
                tracing::warn!(
                    "Ciphers at line {} contains {} ciphers, truncated to first {}",
                    line_number,
                    total_count,
                    MAX_CIPHERS
                );
            }

            if ciphers.is_empty() {
                anyhow::bail!(
                    "Ciphers at line {} must contain at least one valid cipher",
                    line_number
                );
            }

            host.ciphers = ciphers;
        }
        "macs" => {
            if args.is_empty() {
                anyhow::bail!("MACs requires a value at line {line_number}");
            }
            const MAX_MACS: usize = 50;
            const MAX_MAC_NAME_LENGTH: usize = 256;

            let mut macs = Vec::with_capacity(MAX_MACS.min(args.len() * 2));
            let mut total_count = 0;
            let mut truncated = false;

            for arg in args {
                for mac in arg.split(',') {
                    total_count += 1;

                    if macs.len() >= MAX_MACS {
                        truncated = true;
                        break;
                    }

                    let trimmed = mac.trim();
                    if trimmed.is_empty() {
                        continue;
                    }

                    if trimmed.len() > MAX_MAC_NAME_LENGTH {
                        tracing::warn!(
                            "MAC name at line {} exceeds maximum length of {} characters, skipping",
                            line_number,
                            MAX_MAC_NAME_LENGTH
                        );
                        continue;
                    }

                    // Security: Validate MAC name contains only safe characters
                    if !trimmed.chars().all(|c| {
                        c.is_ascii_alphanumeric()
                            || c == '-'
                            || c == '.'
                            || c == '_'
                            || c == '@'
                            || c == '+'
                    }) {
                        anyhow::bail!(
                            "MACs at line {} contains invalid characters in MAC name '{}'. \
                             Only alphanumeric characters, hyphens, dots, underscores, @ and + are allowed",
                            line_number, trimmed
                        );
                    }

                    macs.push(trimmed.to_string());
                }
                if truncated {
                    break;
                }
            }

            if truncated {
                tracing::warn!(
                    "MACs at line {} contains {} MACs, truncated to first {}",
                    line_number,
                    total_count,
                    MAX_MACS
                );
            }

            if macs.is_empty() {
                anyhow::bail!(
                    "MACs at line {} must contain at least one valid MAC",
                    line_number
                );
            }

            host.macs = macs;
        }
        "casignaturealgorithms" => {
            if args.is_empty() {
                anyhow::bail!("CASignatureAlgorithms requires a value at line {line_number}");
            }
            // Security: Limit the number of algorithms to prevent memory exhaustion
            const MAX_ALGORITHMS: usize = 50;
            const MAX_ALGORITHM_NAME_LENGTH: usize = 256;

            let mut algorithms = Vec::with_capacity(MAX_ALGORITHMS.min(args.len() * 2));
            let mut total_count = 0;
            let mut truncated = false;

            // Efficiently parse algorithms without creating unnecessary intermediate strings
            for arg in args {
                // Split each arg by comma and process
                for algorithm in arg.split(',') {
                    total_count += 1;

                    // Stop processing if we've hit the limit
                    if algorithms.len() >= MAX_ALGORITHMS {
                        truncated = true;
                        break;
                    }

                    let trimmed = algorithm.trim();

                    // Skip empty strings from malformed input
                    if trimmed.is_empty() {
                        continue;
                    }

                    // Security: Limit individual algorithm name length
                    if trimmed.len() > MAX_ALGORITHM_NAME_LENGTH {
                        tracing::warn!(
                            "Algorithm name at line {} exceeds maximum length of {} characters, skipping",
                            line_number, MAX_ALGORITHM_NAME_LENGTH
                        );
                        continue;
                    }

                    // Security: Validate algorithm name contains only safe characters
                    // Allow alphanumeric, hyphens, dots, underscores, @ and +
                    if !trimmed.chars().all(|c| {
                        c.is_ascii_alphanumeric()
                            || c == '-'
                            || c == '.'
                            || c == '_'
                            || c == '@'
                            || c == '+'
                    }) {
                        anyhow::bail!(
                            "CASignatureAlgorithms at line {} contains invalid characters in algorithm name '{}'. \
                             Only alphanumeric characters, hyphens, dots, underscores, @ and + are allowed",
                            line_number, trimmed
                        );
                    }

                    algorithms.push(trimmed.to_string());
                }

                if truncated {
                    break;
                }
            }

            if truncated {
                tracing::warn!(
                    "CASignatureAlgorithms at line {} contains {} algorithms, truncated to first {}",
                    line_number, total_count, MAX_ALGORITHMS
                );
            }

            // Ensure we have at least one algorithm
            if algorithms.is_empty() {
                anyhow::bail!(
                    "CASignatureAlgorithms at line {} must contain at least one valid algorithm",
                    line_number
                );
            }

            host.ca_signature_algorithms = algorithms;
        }
        "nohostauthenticationforlocalhost" => {
            if args.is_empty() {
                anyhow::bail!(
                    "NoHostAuthenticationForLocalhost requires a value at line {line_number}"
                );
            }
            let value = parse_yes_no(&args[0], line_number)?;
            if value {
                tracing::debug!(
                    "NoHostAuthenticationForLocalhost enabled at line {} - skipping host verification for localhost (security-sensitive)",
                    line_number
                );
            }
            host.no_host_authentication_for_localhost = Some(value);
        }
        "hashknownhosts" => {
            if args.is_empty() {
                anyhow::bail!("HashKnownHosts requires a value at line {line_number}");
            }
            host.hash_known_hosts = Some(parse_yes_no(&args[0], line_number)?);
        }
        "checkhostip" => {
            if args.is_empty() {
                anyhow::bail!("CheckHostIP requires a value at line {line_number}");
            }
            host.check_host_ip = Some(parse_yes_no(&args[0], line_number)?);
            // Note: CheckHostIP is deprecated in OpenSSH 8.5+ (2021)
            tracing::warn!(
                "CheckHostIP at line {} is deprecated in OpenSSH 8.5+ and may not have effect",
                line_number
            );
        }
        "visualhostkey" => {
            if args.is_empty() {
                anyhow::bail!("VisualHostKey requires a value at line {line_number}");
            }
            host.visual_host_key = Some(parse_yes_no(&args[0], line_number)?);
        }
        "hostkeyalias" => {
            if args.is_empty() {
                anyhow::bail!("HostKeyAlias requires a value at line {line_number}");
            }
            // Security: Validate HostKeyAlias to prevent injection attacks
            // Only allow alphanumeric, dots, hyphens, and underscores (valid hostname characters)
            let alias = &args[0];
            if alias.is_empty() {
                anyhow::bail!("HostKeyAlias cannot be empty at line {line_number}");
            }
            if alias.len() > 255 {
                anyhow::bail!(
                    "HostKeyAlias at line {line_number} exceeds maximum length of 255 characters"
                );
            }
            // Check for dangerous characters that could be used in injection attacks
            if !alias
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_')
            {
                anyhow::bail!(
                    "HostKeyAlias at line {} contains invalid characters. Only alphanumeric, dots, hyphens, and underscores are allowed",
                    line_number
                );
            }
            // Prevent directory traversal
            if alias.contains("..") {
                anyhow::bail!(
                    "HostKeyAlias at line {} contains '..' which could be used for path traversal attacks",
                    line_number
                );
            }
            tracing::debug!(
                "Setting HostKeyAlias to '{}' at line {} (security-sensitive: affects host key verification)",
                alias, line_number
            );
            host.host_key_alias = Some(alias.clone());
        }
        "verifyhostkeydns" => {
            if args.is_empty() {
                anyhow::bail!("VerifyHostKeyDNS requires a value at line {line_number}");
            }
            // Accepts yes/no/ask
            let value = args[0].to_lowercase();
            if !["yes", "no", "ask"].contains(&value.as_str()) {
                anyhow::bail!(
                    "VerifyHostKeyDNS at line {} must be yes, no, or ask, got '{}'",
                    line_number,
                    args[0]
                );
            }
            host.verify_host_key_dns = Some(value);
        }
        "updatehostkeys" => {
            if args.is_empty() {
                anyhow::bail!("UpdateHostKeys requires a value at line {line_number}");
            }
            // Accepts yes/no/ask
            let value = args[0].to_lowercase();
            if !["yes", "no", "ask"].contains(&value.as_str()) {
                anyhow::bail!(
                    "UpdateHostKeys at line {} must be yes, no, or ask, got '{}'",
                    line_number,
                    args[0]
                );
            }
            host.update_host_keys = Some(value);
        }
        "requiredrsasize" => {
            if args.is_empty() {
                anyhow::bail!("RequiredRSASize requires a value at line {line_number}");
            }
            let size: u32 = args[0].parse().with_context(|| {
                format!(
                    "Invalid RequiredRSASize value '{}' at line {}",
                    args[0], line_number
                )
            })?;

            // Security: Enforce reasonable limits to prevent issues
            // OpenSSH minimum is 1024, maximum practical is 16384
            const MIN_RSA_SIZE: u32 = 1024;
            const MAX_RSA_SIZE: u32 = 16384;
            const RECOMMENDED_MIN: u32 = 2048;

            if size < MIN_RSA_SIZE {
                anyhow::bail!(
                    "RequiredRSASize {} at line {} is below minimum allowed value of {}",
                    size,
                    line_number,
                    MIN_RSA_SIZE
                );
            }

            if size > MAX_RSA_SIZE {
                anyhow::bail!(
                    "RequiredRSASize {} at line {} exceeds maximum allowed value of {}",
                    size,
                    line_number,
                    MAX_RSA_SIZE
                );
            }

            // Warn if below recommended minimum (OpenSSH 9.0+ default is 2048)
            if size < RECOMMENDED_MIN {
                tracing::warn!(
                    "RequiredRSASize {} at line {} is below recommended minimum {} (OpenSSH 9.0+ default). \
                     RSA keys smaller than {} bits are considered weak and may be vulnerable to attacks",
                    size,
                    line_number,
                    RECOMMENDED_MIN,
                    RECOMMENDED_MIN
                );
            }

            host.required_rsa_size = Some(size);
        }
        "fingerprinthash" => {
            if args.is_empty() {
                anyhow::bail!("FingerprintHash requires a value at line {line_number}");
            }
            let value = args[0].to_lowercase();
            if !["md5", "sha256"].contains(&value.as_str()) {
                anyhow::bail!(
                    "Invalid FingerprintHash value '{}' at line {} (must be md5 or sha256)",
                    args[0],
                    line_number
                );
            }

            // Warn about MD5 usage (deprecated in OpenSSH 6.8+, default is sha256)
            if value == "md5" {
                tracing::warn!(
                    "FingerprintHash md5 at line {} is deprecated. \
                     OpenSSH 6.8+ (2015) uses sha256 by default. \
                     MD5 should only be used for compatibility with legacy systems",
                    line_number
                );
            }

            host.fingerprint_hash = Some(value);
        }
        _ => unreachable!("Unexpected keyword in parse_security_option: {}", keyword),
    }

    Ok(())
}