-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsshscan.py
More file actions
executable file
·2666 lines (2333 loc) · 116 KB
/
sshscan.py
File metadata and controls
executable file
·2666 lines (2333 loc) · 116 KB
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
SSH Algorithm Security Scanner
Features: Compliance Frameworks, NSA Backdoor Detection, TOML Config,
Retry Logic, DNS Caching, Enhanced Debug Mode, JumpHost/Bastion Function
"""
__version__ = '3.6.4'
__author__ = 'Robert Tulke, rt@debian.sh'
import subprocess
import socket
import json
import sys
import csv
import yaml
import configparser
import threading
import time
import functools
import re
import ipaddress
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import List, Dict, Optional, Tuple, Any, Set
from dataclasses import dataclass, asdict, field
from pathlib import Path
import argparse
import shutil
import io
import logging
from datetime import datetime
# ---------------------------------------------------------------------------
# ANSI color helpers (no external dependency; auto-disabled when not a TTY)
# ---------------------------------------------------------------------------
_C_RESET = '\033[0m'
_C_BOLD = '\033[1m'
_C_DIM = '\033[2m'
_C_RED = '\033[31m'
_C_GREEN = '\033[32m'
_C_YELLOW = '\033[33m'
_C_CYAN = '\033[36m'
def _colorize(text: str, code: str, enabled: bool) -> str:
"""Wrap text in ANSI escape code; no-op when enabled is False."""
return f"{code}{text}{_C_RESET}" if enabled else text
def setup_logging(debug_enabled=False, verbose_enabled=False):
"""Setup logging with proper debug support"""
if debug_enabled:
level = logging.DEBUG
format_str = '%(asctime)s - %(name)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s'
elif verbose_enabled:
level = logging.INFO
format_str = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
else:
level = logging.WARNING
format_str = '%(levelname)s - %(message)s'
logging.basicConfig(
level=level,
format=format_str,
datefmt='%Y-%m-%d %H:%M:%S',
force=True # Override existing configuration
)
# Set specific logger levels for different components
if debug_enabled:
logging.getLogger('SSHEnhancedScanner').setLevel(logging.DEBUG)
logging.getLogger('EnhancedDNSCache').setLevel(logging.DEBUG)
logging.getLogger('AlgorithmTester').setLevel(logging.DEBUG)
return logging.getLogger(__name__)
# Initialize logger (will be reconfigured in main())
logger = logging.getLogger(__name__)
# Custom Exceptions for better error handling
class SSHScannerError(Exception):
"""Base exception for SSH Scanner"""
pass
class ConfigurationError(SSHScannerError):
"""Configuration related errors"""
pass
class SSHConnectionError(SSHScannerError):
"""Connection related errors"""
pass
class ValidationError(SSHScannerError):
"""Input validation errors"""
pass
@dataclass
class SSHAlgorithmInfo:
"""Data class for SSH algorithm information"""
name: str
type: str # 'encryption', 'mac', 'kex', 'hostkey'
supported: bool = True
def __hash__(self):
return hash((self.name, self.type))
@dataclass
class SSHHostResult:
"""Data class for SSH host scan results"""
host: str
port: int
hostname: str = "" # original DNS name if resolved; empty when host was already an IP
status: str = "unknown" # success, failed, timeout, error
security_score: int = 0
compliance_status: Dict[str, bool] = field(default_factory=dict)
nsa_backdoor_analysis: Dict[str, Any] = field(default_factory=dict)
algorithms: Dict[str, List[SSHAlgorithmInfo]] = field(default_factory=dict)
scan_time: float = 0.0
ssh_banner: str = ""
error_message: str = ""
error_type: str = "" # connection, timeout, dns, validation
retry_count: int = 0
timestamp: datetime = field(default_factory=datetime.now)
def to_dict(self) -> dict:
"""Convert to dictionary for serialization"""
result = asdict(self)
result['timestamp'] = self.timestamp.isoformat()
return result
@classmethod
def from_dict(cls, data: dict) -> 'SSHHostResult':
"""Reconstruct an SSHHostResult from a to_dict() payload."""
d = data.copy()
# Rebuild SSHAlgorithmInfo objects from plain dicts
raw_algos = d.pop('algorithms', {})
algorithms: Dict[str, List[SSHAlgorithmInfo]] = {
algo_type: [SSHAlgorithmInfo(**a) for a in algo_list]
for algo_type, algo_list in raw_algos.items()
}
# Parse ISO timestamp string back to datetime
ts = d.pop('timestamp', None)
timestamp = datetime.fromisoformat(ts) if isinstance(ts, str) else (ts or datetime.now())
return cls(algorithms=algorithms, timestamp=timestamp, **d)
@dataclass
class ProxyConfig:
"""Per-host or global proxy / jump-host configuration."""
type: str # 'jump' | 'socks5' | 'http'
host: str # proxy or bastion hostname / IP
port: int = 22 # proxy port (22 for jump, 1080 for socks5, 3128 for http)
user: str = '' # SSH username for jump hosts; unused for SOCKS5/HTTP
def to_ssh_args(self) -> List[str]:
"""Return SSH command-line arguments that route through this proxy."""
host = sanitize_host_input(self.host)
port = validate_port(self.port)
if self.type == 'jump':
user_at = f"{self.user}@" if self.user else ""
return ['-J', f"{user_at}{host}:{port}"]
elif self.type == 'socks5':
return ['-o', f'ProxyCommand=nc -X 5 -x {host}:{port} %h %p']
elif self.type == 'http':
return ['-o', f'ProxyCommand=nc -X connect -x {host}:{port} %h %p']
return []
@classmethod
def from_dict(cls, d: dict) -> Optional['ProxyConfig']:
"""Parse a ``via`` dict from a host file entry. Returns None on error."""
if not isinstance(d, dict):
return None
proxy_type = str(d.get('type', '')).lower()
if proxy_type not in ('jump', 'socks5', 'http'):
logger.warning(f"ProxyConfig: unknown type {proxy_type!r}, must be jump/socks5/http")
return None
host = d.get('host', '')
if not host:
logger.warning("ProxyConfig: missing 'host'")
return None
default_port = 22 if proxy_type == 'jump' else (1080 if proxy_type == 'socks5' else 3128)
try:
port = validate_port(d.get('port', default_port))
except ValidationError:
port = default_port
user_raw = str(d.get('user', ''))
user = re.sub(r'[^a-zA-Z0-9._@-]', '', user_raw)[:64]
return cls(type=proxy_type, host=host, port=port, user=user)
class EnhancedDNSCache:
"""Thread-safe DNS resolution cache with TTL, IPv6 support and background cleanup"""
def __init__(self, ttl: int = 300, max_size: int = 1000, cleanup_interval: int = 60):
self.cache = {}
self.ttl = ttl
self.max_size = max_size
self.cleanup_interval = cleanup_interval
self.lock = threading.Lock()
self.stats = {'hits': 0, 'misses': 0, 'errors': 0, 'cleanups': 0}
self._stop_cleanup = threading.Event()
self._cleanup_thread = None
self._start_cleanup_thread()
logger.debug(f"DNS cache initialized with TTL={ttl}s, max_size={max_size}")
def _start_cleanup_thread(self):
"""Start background cleanup thread"""
self._cleanup_thread = threading.Thread(target=self._cleanup_loop, daemon=True)
self._cleanup_thread.start()
logger.debug("DNS cache cleanup thread started")
def _cleanup_loop(self):
"""Background thread to clean expired entries"""
while not self._stop_cleanup.is_set():
try:
self._cleanup_expired()
self._stop_cleanup.wait(self.cleanup_interval)
except Exception as e:
logger.error(f"DNS cache cleanup error: {e}")
def _cleanup_expired(self):
"""Remove expired entries from cache"""
now = time.time()
with self.lock:
expired_keys = [
hostname for hostname, (_, timestamp) in self.cache.items()
if now - timestamp >= self.ttl
]
for hostname in expired_keys:
del self.cache[hostname]
if expired_keys:
self.stats['cleanups'] += len(expired_keys)
logger.debug(f"Cleaned {len(expired_keys)} expired DNS entries")
def resolve(self, hostname: str, prefer_ipv4: bool = True, ipv6_only: bool = False) -> Optional[str]:
"""Resolve hostname with caching and IPv6 support"""
# Validate hostname first
if not self._is_valid_hostname(hostname):
logger.error(f"Invalid hostname: {hostname}")
return None
# Check if already an IP address
try:
ipaddress.ip_address(hostname)
logger.debug(f"Hostname {hostname} is already an IP address")
return hostname
except ValueError:
pass
now = time.time()
with self.lock:
# Check cache first
if hostname in self.cache:
ip, timestamp = self.cache[hostname]
if now - timestamp < self.ttl:
self.stats['hits'] += 1
logger.debug(f"DNS cache hit for {hostname} -> {ip}")
return ip
# Cache miss - resolve
try:
logger.debug(f"Resolving {hostname} (cache miss)")
# Try both IPv4 and IPv6
addr_info = socket.getaddrinfo(hostname, None, socket.AF_UNSPEC, socket.SOCK_STREAM)
# Filter and sort addresses
ipv4_addrs = []
ipv6_addrs = []
for family, _, _, _, sockaddr in addr_info:
ip = sockaddr[0]
if family == socket.AF_INET:
ipv4_addrs.append(ip)
elif family == socket.AF_INET6:
ipv6_addrs.append(ip)
# Choose based on preference
if ipv6_only:
if ipv6_addrs:
resolved_ip = ipv6_addrs[0]
else:
raise socket.gaierror(f"No IPv6 (AAAA) address found")
elif prefer_ipv4 and ipv4_addrs:
resolved_ip = ipv4_addrs[0]
elif ipv6_addrs:
resolved_ip = ipv6_addrs[0]
elif ipv4_addrs:
resolved_ip = ipv4_addrs[0]
else:
raise socket.gaierror("No addresses found")
with self.lock:
# Manage cache size
if len(self.cache) >= self.max_size:
# Remove oldest entry
oldest_key = min(self.cache.keys(), key=lambda k: self.cache[k][1])
del self.cache[oldest_key]
self.cache[hostname] = (resolved_ip, now)
self.stats['misses'] += 1
logger.debug(f"Resolved {hostname} to {resolved_ip}")
return resolved_ip
except (socket.gaierror, socket.error) as e:
with self.lock:
self.stats['errors'] += 1
logger.warning(f"DNS resolution failed for {hostname}: {e}")
return None
def _is_valid_hostname(self, hostname: str) -> bool:
"""Validate hostname to prevent injection attacks"""
if not hostname or len(hostname) > 253:
return False
# Accept IPv6 literals (e.g. "2001:db8::1", "::1") before the DNS-name regex
try:
ipaddress.ip_address(hostname)
return True
except ValueError:
pass
# Check for valid DNS-name characters: letters, digits, dot, hyphen
allowed = re.match(r'^[a-zA-Z0-9.-]+$', hostname)
if not allowed:
return False
# Check each label
labels = hostname.split('.')
for label in labels:
if not label or len(label) > 63:
return False
if label.startswith('-') or label.endswith('-'):
return False
return True
def get_stats(self) -> Dict:
"""Get cache statistics"""
with self.lock:
total = self.stats['hits'] + self.stats['misses']
hit_rate = (self.stats['hits'] / total * 100) if total > 0 else 0
return {
'hit_rate': f"{hit_rate:.1f}%",
'total_lookups': total,
'cache_size': len(self.cache),
'expired_cleaned': self.stats['cleanups'],
**self.stats
}
def stop(self):
"""Stop cleanup thread"""
self._stop_cleanup.set()
if self._cleanup_thread:
self._cleanup_thread.join(timeout=1)
def validate_port(port: Any) -> int:
"""Validate and convert port number"""
try:
port_int = int(port)
if not 1 <= port_int <= 65535:
raise ValidationError(f"Port {port} out of valid range (1-65535)")
return port_int
except (ValueError, TypeError):
raise ValidationError(f"Invalid port: {port}")
def validate_ip_address(ip: str) -> bool:
"""Validate IP address (v4 or v6)"""
try:
ipaddress.ip_address(ip)
return True
except ValueError:
return False
def sanitize_host_input(host: str) -> str:
"""Sanitize host input — allowlist of valid hostname/IP/bracket characters."""
host = host.strip()
# Allow: letters, digits, dot, hyphen, colon (port sep / IPv6), brackets (IPv6), underscore, percent (scope)
host = re.sub(r'[^a-zA-Z0-9.\-:\[\]_%]', '', host)
if len(host) > 253: # Max DNS name length
raise ValidationError(f"Hostname too long: {host}")
return host
class ConfigValidator:
"""Validate and sanitize configuration options"""
VALID_FRAMEWORKS = ['NIST', 'FIPS_140_2', 'BSI_TR_02102', 'ANSSI', 'PRIVACY_FOCUSED']
@staticmethod
def validate_config(config: Dict) -> Dict:
"""Validate configuration dictionary"""
validated = {}
# Scanner configuration
scanner_config = config.get('scanner', {})
validated['scanner'] = {}
# Validate threads
threads = scanner_config.get('threads', 20)
try:
threads = int(threads)
if not 1 <= threads <= 500:
raise ValueError
validated['scanner']['threads'] = threads
except (ValueError, TypeError):
logger.warning(f"Invalid threads value: {threads}, using default 20")
validated['scanner']['threads'] = 20
# Validate timeout
timeout = scanner_config.get('timeout', 10)
try:
timeout = int(timeout)
if not 1 <= timeout <= 120:
raise ValueError
validated['scanner']['timeout'] = timeout
except (ValueError, TypeError):
logger.warning(f"Invalid timeout value: {timeout}, using default 10")
validated['scanner']['timeout'] = 10
# Validate retry_attempts
retry = scanner_config.get('retry_attempts', 3)
try:
retry = int(retry)
if not 1 <= retry <= 10:
raise ValueError
validated['scanner']['retry_attempts'] = retry
except (ValueError, TypeError):
logger.warning(f"Invalid retry_attempts value: {retry}, using default 3")
validated['scanner']['retry_attempts'] = 3
# Validate dns_cache_ttl
dns_ttl = scanner_config.get('dns_cache_ttl', 300)
try:
dns_ttl = int(dns_ttl)
if not 60 <= dns_ttl <= 3600:
raise ValueError
validated['scanner']['dns_cache_ttl'] = dns_ttl
except (ValueError, TypeError):
logger.warning(f"Invalid dns_cache_ttl value: {dns_ttl}, using default 300")
validated['scanner']['dns_cache_ttl'] = 300
# Validate banner_timeout (optional — None = min(timeout, 5))
banner_timeout = scanner_config.get('banner_timeout', None)
if banner_timeout is not None:
try:
banner_timeout = int(banner_timeout)
if not 1 <= banner_timeout <= 30:
raise ValueError
validated['scanner']['banner_timeout'] = banner_timeout
except (ValueError, TypeError):
logger.warning(f"Invalid banner_timeout value: {banner_timeout}, ignoring (valid range: 1-30)")
# Validate rate_limit (optional — None = unlimited)
rate_limit = scanner_config.get('rate_limit', None)
if rate_limit is not None:
try:
rate_limit = float(rate_limit)
if not 0.1 <= rate_limit <= 1000:
raise ValueError
validated['scanner']['rate_limit'] = rate_limit
except (ValueError, TypeError):
logger.warning(f"Invalid rate_limit value: {rate_limit}, ignoring (valid range: 0.1-1000)")
# Validate strict_host_key_checking (optional — default: accept-new)
_SSHKC_VALUES = ('yes', 'no', 'accept-new')
sshkc = scanner_config.get('strict_host_key_checking', 'accept-new')
if sshkc in _SSHKC_VALUES:
validated['scanner']['strict_host_key_checking'] = sshkc
else:
logger.warning(f"Invalid strict_host_key_checking value: {sshkc!r}, "
f"using 'accept-new' (valid: {', '.join(_SSHKC_VALUES)})")
validated['scanner']['strict_host_key_checking'] = 'accept-new'
# jump_host (optional — None = no jump host)
jump_host = scanner_config.get('jump_host', None)
if jump_host:
validated['scanner']['jump_host'] = str(jump_host).strip()
# proxy_command (optional — raw ProxyCommand string, passed through as-is)
proxy_command = scanner_config.get('proxy_command', None)
if proxy_command:
validated['scanner']['proxy_command'] = str(proxy_command).strip()
# Compliance configuration (optional — no framework = no compliance check)
compliance_config = config.get('compliance', {})
validated['compliance'] = {}
framework = compliance_config.get('framework', None)
if framework is not None:
if framework in ConfigValidator.VALID_FRAMEWORKS:
validated['compliance']['framework'] = framework
else:
logger.warning(f"Invalid compliance framework: {framework}, ignoring")
return validated
def retry_on_failure(max_attempts: int = 3, backoff_factor: float = 2.0, exceptions: Tuple = None):
"""Decorator for retry logic with exponential backoff"""
if exceptions is None:
exceptions = (subprocess.TimeoutExpired, subprocess.CalledProcessError, SSHConnectionError)
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
last_exception = None
retry_count = 0
for attempt in range(max_attempts):
try:
return func(*args, **kwargs)
except exceptions as e:
last_exception = e
retry_count += 1
if attempt < max_attempts - 1:
sleep_time = backoff_factor ** attempt
logger.debug(f"Attempt {attempt + 1} failed: {e}. Retrying in {sleep_time:.1f}s...")
time.sleep(sleep_time)
else:
logger.warning(f"All {max_attempts} attempts failed for {func.__name__}")
raise last_exception
return wrapper
return decorator
class NSABackdoorDetector:
"""Detection of algorithms with suspected NSA backdoors"""
# Algorithms with suspected NSA involvement/backdoors
SUSPECTED_NSA_ALGORITHMS = {
'kex': {
'ecdh-sha2-nistp256': {
'risk': 'HIGH',
'reason': 'NIST P-256 curve - NSA involvement in curve selection',
'alternative': 'curve25519-sha256',
'reference': 'Snowden revelations, SafeCurves project'
},
'ecdh-sha2-nistp384': {
'risk': 'HIGH',
'reason': 'NIST P-384 curve - NSA involvement in curve selection',
'alternative': 'curve25519-sha256',
'reference': 'Snowden revelations, SafeCurves project'
},
'ecdh-sha2-nistp521': {
'risk': 'HIGH',
'reason': 'NIST P-521 curve - NSA involvement in curve selection',
'alternative': 'curve25519-sha256',
'reference': 'Snowden revelations, SafeCurves project'
}
},
'key': {
'ecdsa-sha2-nistp256': {
'risk': 'HIGH',
'reason': 'ECDSA with NIST P-256 - potential NSA backdoor in curve',
'alternative': 'ssh-ed25519',
'reference': 'NSA Suite B cryptography concerns'
},
'ecdsa-sha2-nistp384': {
'risk': 'HIGH',
'reason': 'ECDSA with NIST P-384 - potential NSA backdoor in curve',
'alternative': 'ssh-ed25519',
'reference': 'NSA Suite B cryptography concerns'
},
'ecdsa-sha2-nistp521': {
'risk': 'HIGH',
'reason': 'ECDSA with NIST P-521 - potential NSA backdoor in curve',
'alternative': 'ssh-ed25519',
'reference': 'NSA Suite B cryptography concerns'
},
'ecdsa-sha2-nistp256-cert-v01@openssh.com': {
'risk': 'HIGH',
'reason': 'ECDSA certificate with NIST P-256 - same curve concerns',
'alternative': 'ssh-ed25519-cert-v01@openssh.com',
'reference': 'NSA Suite B cryptography concerns'
},
'ecdsa-sha2-nistp384-cert-v01@openssh.com': {
'risk': 'HIGH',
'reason': 'ECDSA certificate with NIST P-384 - same curve concerns',
'alternative': 'ssh-ed25519-cert-v01@openssh.com',
'reference': 'NSA Suite B cryptography concerns'
},
'ecdsa-sha2-nistp521-cert-v01@openssh.com': {
'risk': 'HIGH',
'reason': 'ECDSA certificate with NIST P-521 - same curve concerns',
'alternative': 'ssh-ed25519-cert-v01@openssh.com',
'reference': 'NSA Suite B cryptography concerns'
},
'sk-ecdsa-sha2-nistp256@openssh.com': {
'risk': 'HIGH',
'reason': 'FIDO/SK ECDSA with NIST P-256 - same curve concerns',
'alternative': 'sk-ssh-ed25519@openssh.com',
'reference': 'NSA Suite B cryptography concerns'
},
'sk-ecdsa-sha2-nistp256-cert-v01@openssh.com': {
'risk': 'HIGH',
'reason': 'FIDO/SK ECDSA certificate with NIST P-256 - same curve concerns',
'alternative': 'sk-ssh-ed25519-cert-v01@openssh.com',
'reference': 'NSA Suite B cryptography concerns'
},
},
'cipher': {
# Historical NSA involvement
'des': {
'risk': 'CRITICAL',
'reason': 'NSA involvement in S-box design, weak key size',
'alternative': 'aes256-gcm@openssh.com',
'reference': 'Historical NSA involvement in DES design'
}
},
'mac': {
'hmac-sha1': {
'risk': 'MEDIUM',
'reason': 'SHA-1 developed with NSA involvement, collision attacks',
'alternative': 'hmac-sha2-256-etm@openssh.com',
'reference': 'SHA-1 cryptanalysis and NSA design'
},
'hmac-sha1-etm@openssh.com': {
'risk': 'MEDIUM',
'reason': 'SHA-1 with NSA involvement (ETM variant)',
'alternative': 'hmac-sha2-256-etm@openssh.com',
'reference': 'SHA-1 cryptanalysis and NSA design'
},
}
}
@classmethod
def check_nsa_backdoor_risk(cls, algorithms: Dict[str, List[SSHAlgorithmInfo]], check_enabled: bool = True) -> Dict:
"""Check for algorithms with suspected NSA backdoors"""
backdoor_analysis = {
'enabled': check_enabled,
'high_risk_algorithms': [],
'medium_risk_algorithms': [],
'confirmed_backdoors': [],
'recommendations': [],
'overall_risk_score': 0,
'trusted_alternatives': []
}
if not check_enabled:
backdoor_analysis['status'] = 'disabled'
return backdoor_analysis
total_algorithms = 0
risky_algorithms = 0
for algo_type, algo_list in algorithms.items():
for algo in algo_list:
if algo.supported:
total_algorithms += 1
# Check for suspected backdoors
if algo_type in cls.SUSPECTED_NSA_ALGORITHMS:
if algo.name in cls.SUSPECTED_NSA_ALGORITHMS[algo_type]:
risky_algorithms += 1
risk_info = cls.SUSPECTED_NSA_ALGORITHMS[algo_type][algo.name]
risk_entry = {
'algorithm': algo.name,
'type': algo_type,
'risk_level': risk_info['risk'],
'reason': risk_info['reason'],
'recommended_alternative': risk_info['alternative'],
'reference': risk_info['reference']
}
if risk_info['risk'] == 'HIGH' or risk_info['risk'] == 'CRITICAL':
backdoor_analysis['high_risk_algorithms'].append(risk_entry)
else:
backdoor_analysis['medium_risk_algorithms'].append(risk_entry)
# Calculate overall risk score
if total_algorithms > 0:
risk_percentage = (risky_algorithms / total_algorithms) * 100
backdoor_analysis['overall_risk_score'] = min(100, risk_percentage * 2) # Amplify risk
# Generate recommendations
if backdoor_analysis['high_risk_algorithms']:
backdoor_analysis['recommendations'].extend([
'CRITICAL: Replace NIST P-curve algorithms with Curve25519/Ed25519',
'Avoid ECDH/ECDSA with NIST curves (P-256, P-384, P-521)',
'Use independently developed cryptographic primitives',
'Consider SafeCurves.cr.yp.to recommendations'
])
# Trusted alternatives
backdoor_analysis['trusted_alternatives'] = [
'curve25519-sha256 (Key Exchange)',
'ssh-ed25519 (Host Keys)',
'aes256-gcm@openssh.com (Encryption)',
'chacha20-poly1305@openssh.com (Encryption)',
'hmac-sha2-256-etm@openssh.com (MAC)'
]
return backdoor_analysis
class ComplianceFramework:
"""SSH compliance framework definitions with NSA backdoor awareness"""
FRAMEWORKS = {
'PRIVACY_FOCUSED': {
'name': 'Privacy-Focused Anti-Surveillance Framework',
'required_ciphers': [
'chacha20-poly1305@openssh.com', 'aes256-gcm@openssh.com'
],
'forbidden_ciphers': [
'des', '3des-cbc', 'blowfish-cbc', 'cast128-cbc', 'arcfour', 'arcfour128', 'arcfour256',
'aes128-cbc', 'aes192-cbc', 'aes256-cbc'
],
'required_mac': [
'hmac-sha2-256-etm@openssh.com', 'hmac-sha2-512-etm@openssh.com'
],
'forbidden_mac': [
# Non-ETM (MAC-then-Encrypt, vulnerable to padding oracle attacks)
'hmac-sha2-256', 'hmac-sha2-512', 'umac-128@openssh.com',
# SHA-1 based (NSA involvement, collision attacks known)
'hmac-sha1', 'hmac-sha1-96', 'hmac-sha1-etm@openssh.com', 'hmac-sha1-96-etm@openssh.com',
# MD5 based (broken)
'hmac-md5', 'hmac-md5-96', 'hmac-md5-etm@openssh.com', 'hmac-md5-96-etm@openssh.com',
# 64-bit UMAC (tag too short)
'umac-64', 'umac-64@openssh.com', 'umac-64-etm@openssh.com',
],
'required_kex': [
'curve25519-sha256', 'curve25519-sha256@libssh.org'
],
'forbidden_kex': [
'diffie-hellman-group1-sha1', 'diffie-hellman-group14-sha1',
'diffie-hellman-group-exchange-sha1',
# NSA-suspicious NIST curves
'ecdh-sha2-nistp256', 'ecdh-sha2-nistp384', 'ecdh-sha2-nistp521'
],
'required_hostkey': [
'ssh-ed25519'
],
'forbidden_hostkey': [
# DSA (broken)
'ssh-dss', 'ssh-dss-cert-v01@openssh.com',
# RSA (weak if < 2048 bit; cert chains not auditable)
'ssh-rsa', 'ssh-rsa-cert-v01@openssh.com',
# NSA NIST ECDSA — plain, cert, and FIDO/SK variants
'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', 'ecdsa-sha2-nistp521',
'ecdsa-sha2-nistp256-cert-v01@openssh.com',
'ecdsa-sha2-nistp384-cert-v01@openssh.com',
'ecdsa-sha2-nistp521-cert-v01@openssh.com',
'sk-ecdsa-sha2-nistp256@openssh.com',
'sk-ecdsa-sha2-nistp256-cert-v01@openssh.com',
],
'minimum_score': 95
},
'NIST': {
'name': 'NIST SP 800-53 / IR 7966',
'required_ciphers': [
'aes256-ctr', 'aes128-ctr'
],
'forbidden_ciphers': [
'des', '3des-cbc', 'blowfish-cbc', 'cast128-cbc',
'arcfour', 'arcfour128', 'arcfour256', 'aes128-cbc', 'aes192-cbc', 'aes256-cbc'
],
'required_mac': [
'hmac-sha2-256', 'hmac-sha2-512'
],
'forbidden_mac': [
'hmac-md5', 'hmac-md5-96', 'hmac-sha1', 'hmac-sha1-96', 'umac-64'
],
'required_kex': [
'ecdh-sha2-nistp256'
],
'forbidden_kex': [
'diffie-hellman-group1-sha1', 'diffie-hellman-group14-sha1',
'diffie-hellman-group-exchange-sha1'
],
'required_hostkey': [
'ecdsa-sha2-nistp256'
],
'forbidden_hostkey': [
'ssh-dss', 'ssh-rsa'
],
'minimum_score': 80
},
'FIPS_140_2': {
'name': 'FIPS 140-2 Level 1',
'required_ciphers': [
'aes256-ctr', 'aes192-ctr', 'aes128-ctr'
],
'forbidden_ciphers': [
'des', '3des-cbc', 'blowfish-cbc', 'cast128-cbc', 'arcfour', 'arcfour128', 'arcfour256',
# Not FIPS 140-2 approved
'chacha20-poly1305@openssh.com',
],
'required_mac': [
'hmac-sha2-256', 'hmac-sha2-512'
],
'forbidden_mac': [
'hmac-md5', 'hmac-md5-96', 'hmac-sha1', 'hmac-sha1-96'
],
'required_kex': [
'ecdh-sha2-nistp256'
],
'forbidden_kex': [
'diffie-hellman-group1-sha1', 'diffie-hellman-group14-sha1',
# Not FIPS 140-2 approved (Curve25519 / non-NIST curves)
'curve25519-sha256', 'curve25519-sha256@libssh.org',
'sntrup761x25519-sha512@openssh.com', 'sntrup761x25519-sha512',
'mlkem768x25519-sha256',
],
'required_hostkey': [
'ecdsa-sha2-nistp256'
],
'forbidden_hostkey': [
'ssh-dss',
'ssh-rsa', # SHA-1 based signature
# Not FIPS 140-2 approved (Ed25519 = Curve25519-based)
'ssh-ed25519', 'ssh-ed25519-cert-v01@openssh.com',
'sk-ssh-ed25519@openssh.com', 'sk-ssh-ed25519-cert-v01@openssh.com',
],
'minimum_score': 90
},
'BSI_TR_02102': {
'name': 'BSI TR-02102-4 (German Federal Office)',
'required_ciphers': [
'aes256-gcm@openssh.com', 'aes256-ctr', 'chacha20-poly1305@openssh.com'
],
'forbidden_ciphers': [
'des', '3des-cbc', 'blowfish-cbc', 'cast128-cbc', 'arcfour', 'arcfour128', 'arcfour256',
'aes128-cbc', 'aes192-cbc', 'aes256-cbc'
],
'required_mac': [
'hmac-sha2-256-etm@openssh.com', 'hmac-sha2-512-etm@openssh.com'
],
'forbidden_mac': [
'hmac-md5', 'hmac-md5-96', 'hmac-sha1', 'hmac-sha1-96', 'umac-64'
],
'required_kex': [
'curve25519-sha256', 'curve25519-sha256@libssh.org'
],
'forbidden_kex': [
'diffie-hellman-group1-sha1', 'diffie-hellman-group14-sha1',
'diffie-hellman-group-exchange-sha1',
],
'required_hostkey': [
'ssh-ed25519'
],
'forbidden_hostkey': [
'ssh-dss', 'ssh-rsa', 'ecdsa-sha2-nistp256'
],
'minimum_score': 85
},
'ANSSI': {
'name': 'ANSSI (French National Cybersecurity Agency)',
'required_ciphers': [
'aes256-gcm@openssh.com', 'chacha20-poly1305@openssh.com'
],
'forbidden_ciphers': [
'des', '3des-cbc', 'blowfish-cbc', 'cast128-cbc', 'arcfour', 'arcfour128', 'arcfour256',
'aes128-cbc', 'aes192-cbc', 'aes256-cbc', 'aes128-ctr'
],
'required_mac': [
'hmac-sha2-256-etm@openssh.com', 'hmac-sha2-512-etm@openssh.com'
],
'forbidden_mac': [
'hmac-md5', 'hmac-md5-96', 'hmac-sha1', 'hmac-sha1-96', 'umac-64', 'umac-128@openssh.com'
],
'required_kex': [
'curve25519-sha256', 'curve25519-sha256@libssh.org'
],
'forbidden_kex': [
'diffie-hellman-group1-sha1', 'diffie-hellman-group14-sha1',
'diffie-hellman-group-exchange-sha1', 'ecdh-sha2-nistp256'
],
'required_hostkey': [
'ssh-ed25519'
],
'forbidden_hostkey': [
'ssh-dss', 'ssh-rsa', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', 'ecdsa-sha2-nistp521'
],
'minimum_score': 95
}
}
@classmethod
def check_compliance(cls, algorithms: Dict[str, List[SSHAlgorithmInfo]], framework: str,
security_score: int = None) -> Dict[str, bool]:
"""Check compliance against specified framework"""
if framework not in cls.FRAMEWORKS:
raise ValueError(f"Unknown framework: {framework}")
fw = cls.FRAMEWORKS[framework]
compliance_result = {}
# Get supported algorithms by type
supported_by_type = {}
for algo_type, algo_list in algorithms.items():
supported_by_type[algo_type] = [algo.name for algo in algo_list if algo.supported]
# Map internal types to framework types
type_mapping = {
'cipher': 'ciphers',
'mac': 'mac',
'kex': 'kex',
'key': 'hostkey'
}
for internal_type, fw_type in type_mapping.items():
if internal_type in supported_by_type:
supported = set(supported_by_type[internal_type])
# Check required algorithms
required_key = f'required_{fw_type}'
if required_key in fw:
required = set(fw[required_key])
has_required = required.issubset(supported)
compliance_result[f'{fw_type}_has_required'] = has_required
# Check forbidden algorithms
forbidden_key = f'forbidden_{fw_type}'
if forbidden_key in fw:
forbidden = set(fw[forbidden_key])
has_forbidden = bool(forbidden & supported)
compliance_result[f'{fw_type}_has_forbidden'] = has_forbidden
# Overall compliance (algorithm checks)
algo_compliant = (
all(v for k, v in compliance_result.items() if 'has_required' in k) and
not any(v for k, v in compliance_result.items() if 'has_forbidden' in k)
)
# Minimum score check
min_score = fw.get('minimum_score')
if min_score is not None and security_score is not None:
compliance_result['minimum_score_required'] = min_score
score_ok = security_score >= min_score
compliance_result['score_meets_minimum'] = score_ok
compliance_result['overall_compliant'] = algo_compliant and score_ok
else:
compliance_result['overall_compliant'] = algo_compliant
return compliance_result
@classmethod
def get_framework_list(cls) -> List[str]:
"""Get list of available frameworks"""
return list(cls.FRAMEWORKS.keys())
@classmethod
def get_framework_info(cls, framework: str) -> Dict:
"""Get framework information"""
return cls.FRAMEWORKS.get(framework, {})
class AlgorithmTester:
"""Handles algorithm testing with parallelization"""
def __init__(self, test_function, max_workers: int = 5):
self.test_function = test_function
self.max_workers = max_workers
logger.debug(f"Algorithm tester initialized with {max_workers} workers")
def test_algorithms_parallel(self, host: str, port: int, algorithms: Dict[str, List[str]],
line_callback=None) -> Dict[str, List[SSHAlgorithmInfo]]:
"""Test algorithms in parallel for a single host"""
results = {}
with ThreadPoolExecutor(max_workers=self.max_workers) as executor:
future_to_algo = {}
for algo_type, algo_list in algorithms.items():
results[algo_type] = []
for algorithm in algo_list:
future = executor.submit(self.test_function, host, algorithm, algo_type, port)
future_to_algo[future] = (algo_type, algorithm)
logger.debug(f"Submitted {len(future_to_algo)} algorithm tests for {host}:{port}")
for future in as_completed(future_to_algo):
algo_type, algorithm = future_to_algo[future]
try:
is_supported = future.result()
results[algo_type].append(SSHAlgorithmInfo(
name=algorithm, type=algo_type, supported=is_supported
))
if line_callback:
line_callback(algo_type, algorithm, is_supported)
logger.debug(f"Algorithm test completed: {algorithm} ({'supported' if is_supported else 'not supported'})")