-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdev_env_check.py
More file actions
1117 lines (929 loc) · 49.7 KB
/
Copy pathdev_env_check.py
File metadata and controls
1117 lines (929 loc) · 49.7 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
"""
Local Development Environment Checker
Checks various files, tools, and configurations on the local dev machine.
"""
import os
import subprocess
import sys
from pathlib import Path
from typing import Dict, List, Tuple, Optional
import json
import argparse
# Color codes for terminal output
class Colors:
GREEN = '\033[92m'
RED = '\033[91m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
BOLD = '\033[1m'
END = '\033[0m'
class DevEnvChecker:
def __init__(self, project_path: Optional[str] = None):
self.project_path = project_path
self.results = []
if self.project_path:
self.project_path = os.path.expanduser(self.project_path)
self.custom_hosts_entries = []
def add_result(self, category: str, item: str, status: str, details: str = ""):
"""Add a check result to the results list"""
self.results.append({
'category': category,
'item': item,
'status': status,
'details': details
})
def print_status(self, status: str) -> str:
"""Return colored status indicator"""
if status == "OK":
return f"{Colors.GREEN}✅ OK{Colors.END}"
elif status == "MISSING":
return f"{Colors.RED}❌ MISSING{Colors.END}"
elif status == "ERROR":
return f"{Colors.RED}❌ ERROR{Colors.END}"
elif status == "WARNING":
return f"{Colors.YELLOW}⚠️ WARNING{Colors.END}"
else:
return f"{Colors.BLUE}ℹ️ {status}{Colors.END}"
def check_file_exists(self, filepath: str, category: str, description: str):
"""Check if a file exists"""
expanded_path = os.path.expanduser(filepath)
if os.path.exists(expanded_path):
# Get file size for additional info
size = os.path.getsize(expanded_path)
self.add_result(category, description, "OK", f"Size: {size} bytes")
else:
self.add_result(category, description, "MISSING", f"Path: {expanded_path}")
def check_command_exists(self, command: str, category: str, description: str):
"""Check if a command exists and is executable"""
try:
result = subprocess.run(['which', command], capture_output=True, text=True)
if result.returncode == 0:
path = result.stdout.strip()
self.add_result(category, description, "OK", f"Path: {path}")
return True
else:
self.add_result(category, description, "MISSING", "Command not found")
return False
except Exception as e:
self.add_result(category, description, "ERROR", str(e))
return False
def check_command_version(self, command: str, category: str, description: str, version_flag: str = "--version"):
"""Check command version"""
if not self.check_command_exists(command, category, f"{description} (installed)"):
return
try:
result = subprocess.run([command, version_flag], capture_output=True, text=True, timeout=10)
if result.returncode == 0:
version = result.stdout.strip().split('\n')[0] # First line usually contains version
self.add_result(category, f"{description} (version)", "OK", version)
else:
self.add_result(category, f"{description} (version)", "ERROR", result.stderr.strip())
except subprocess.TimeoutExpired:
self.add_result(category, f"{description} (version)", "ERROR", "Command timeout")
except Exception as e:
self.add_result(category, f"{description} (version)", "ERROR", str(e))
def check_aws_credentials_file(self):
"""Analyze AWS credentials file for profiles"""
aws_creds_path = os.path.expanduser("~/.aws/credentials")
if not os.path.exists(aws_creds_path):
self.add_result("AWS", "Credentials file", "MISSING", f"Path: {aws_creds_path}")
return
try:
with open(aws_creds_path, 'r') as f:
content = f.read()
# Parse profiles from credentials file
profiles = []
lines = content.split('\n')
for line in lines:
line = line.strip()
if line.startswith('[') and line.endswith(']'):
profile_name = line[1:-1] # Remove brackets
profiles.append(profile_name)
# Create summary
if profiles:
if len(profiles) == 1:
summary = f"Profiles: 1 ({profiles[0]})"
elif len(profiles) <= 5:
profile_list = ', '.join(profiles)
summary = f"Profiles: {len(profiles)} ({profile_list})"
else:
summary = f"Profiles: {len(profiles)}"
self.add_result("AWS", "Credentials file", "OK", summary)
else:
self.add_result("AWS", "Credentials file", "WARNING", "No profiles found")
except PermissionError:
self.add_result("AWS", "Credentials file", "ERROR", "Permission denied")
except Exception as e:
self.add_result("AWS", "Credentials file", "ERROR", f"Failed to parse: {str(e)}")
def check_aws_config_file(self):
"""Analyze AWS config file for regions and settings"""
aws_config_path = os.path.expanduser("~/.aws/config")
if not os.path.exists(aws_config_path):
self.add_result("AWS", "Config file", "MISSING", f"Path: {aws_config_path}")
return
try:
with open(aws_config_path, 'r') as f:
content = f.read()
# Parse config settings
lines = content.split('\n')
default_region = None
default_output = None
regions = set()
profiles = []
current_profile = None
for line in lines:
line = line.strip()
if not line or line.startswith('#'):
continue
if line.startswith('[') and line.endswith(']'):
profile_name = line[1:-1] # Remove brackets
if profile_name.startswith('profile '):
profile_name = profile_name[8:] # Remove 'profile ' prefix
current_profile = profile_name
profiles.append(profile_name)
elif '=' in line:
key, value = line.split('=', 1)
key = key.strip()
value = value.strip()
if key == 'region':
regions.add(value)
if current_profile == 'default' or default_region is None:
default_region = value
elif key == 'output' and current_profile == 'default':
default_output = value
# Create summary
summary_parts = []
if default_region:
summary_parts.append(f"Region: {default_region}")
if default_output:
summary_parts.append(f"Output: {default_output}")
if len(regions) > 1:
summary_parts.append(f"Multiple regions: {len(regions)}")
if len(profiles) > 1:
summary_parts.append(f"Profiles: {len(profiles)}")
if summary_parts:
summary = ", ".join(summary_parts)
self.add_result("AWS", "Config file", "OK", summary)
else:
self.add_result("AWS", "Config file", "OK", "Basic configuration")
except PermissionError:
self.add_result("AWS", "Config file", "ERROR", "Permission denied")
except Exception as e:
self.add_result("AWS", "Config file", "ERROR", f"Failed to parse: {str(e)}")
def check_aws_credentials(self):
"""Check AWS credentials and connectivity with intelligent analysis"""
# Analyze credentials file
self.check_aws_credentials_file()
# Analyze config file
self.check_aws_config_file()
# Test AWS CLI connectivity
if self.check_command_exists("aws", "AWS", "AWS CLI"):
try:
result = subprocess.run(['aws', 'sts', 'get-caller-identity'],
capture_output=True, text=True, timeout=15)
if result.returncode == 0:
identity = json.loads(result.stdout)
user_info = identity.get('Arn', 'Unknown user')
self.add_result("AWS", "API connectivity", "OK", user_info)
else:
self.add_result("AWS", "API connectivity", "ERROR", result.stderr.strip())
except subprocess.TimeoutExpired:
self.add_result("AWS", "API connectivity", "ERROR", "Request timeout")
except Exception as e:
self.add_result("AWS", "API connectivity", "ERROR", str(e))
def check_gcp_credentials_file(self):
"""Analyze GCP application credentials file"""
gcp_creds_path = os.path.expanduser("~/.config/gcloud/application_default_credentials.json")
if not os.path.exists(gcp_creds_path):
self.add_result("GCP", "Application credentials", "MISSING", f"Path: {gcp_creds_path}")
return
try:
with open(gcp_creds_path, 'r') as f:
creds_data = json.load(f)
# Extract useful information
summary_parts = []
# Credential type
cred_type = creds_data.get('type', 'unknown')
if cred_type == 'authorized_user':
summary_parts.append("Type: User")
elif cred_type == 'service_account':
summary_parts.append("Type: Service Account")
else:
summary_parts.append(f"Type: {cred_type}")
# Project ID (quota_project_id is the active project)
project_id = creds_data.get('quota_project_id') or creds_data.get('project_id')
if project_id:
summary_parts.append(f"Project: {project_id}")
# Universe domain (for specialized GCP environments)
universe = creds_data.get('universe_domain', 'googleapis.com')
if universe != 'googleapis.com':
summary_parts.append(f"Domain: {universe}")
# Service account email (if service account)
if cred_type == 'service_account':
client_email = creds_data.get('client_email')
if client_email:
summary_parts.append(f"SA: {client_email.split('@')[0]}")
if summary_parts:
summary = ", ".join(summary_parts)
self.add_result("GCP", "Application credentials", "OK", summary)
else:
self.add_result("GCP", "Application credentials", "OK", "Valid credentials")
except json.JSONDecodeError:
self.add_result("GCP", "Application credentials", "ERROR", "Invalid JSON format")
except PermissionError:
self.add_result("GCP", "Application credentials", "ERROR", "Permission denied")
except Exception as e:
self.add_result("GCP", "Application credentials", "ERROR", f"Failed to parse: {str(e)}")
def check_netlify_cli(self):
"""Check Netlify CLI status and configuration"""
# Check for global config file
netlify_config_path = os.path.expanduser("~/.config/netlify/config.json")
if os.path.exists(netlify_config_path):
try:
with open(netlify_config_path, 'r') as f:
config = json.load(f)
user_id = config.get('userId')
details = f"User ID: {user_id}" if user_id else "Logged out"
self.add_result("Netlify", "Global config", "OK", details)
except Exception as e:
self.add_result("Netlify", "Global config", "ERROR", f"Failed to parse: {str(e)}")
else:
self.add_result("Netlify", "Global config", "MISSING", f"Path: {netlify_config_path}")
# Check for CLI and status, using project path if provided
if self.check_command_exists("netlify", "Netlify", "Netlify CLI"):
try:
cwd = None
if self.project_path:
if os.path.isdir(self.project_path):
cwd = self.project_path
self.add_result("Netlify", "Project context", "OK", f"Using path: {self.project_path}")
else:
self.add_result("Netlify", "Project context", "ERROR", f"Directory not found: {self.project_path}")
return
result = subprocess.run(['netlify', 'status'], capture_output=True, text=True, timeout=15, cwd=cwd)
if result.returncode == 0:
# Extract user email from status
user_email = "Unknown"
for line in result.stdout.split('\n'):
# Handle different output formats from 'netlify status'
if 'Netlify User:' in line:
user_email = line.split('Netlify User:')[1].strip()
break
elif 'Email:' in line:
user_email = line.split('Email:')[1].strip()
break
self.add_result("Netlify", "Authentication", "OK", f"Logged in as: {user_email}")
else:
self.add_result("Netlify", "Authentication", "WARNING", "Not logged in")
except subprocess.TimeoutExpired:
self.add_result("Netlify", "Authentication", "ERROR", "Request timeout")
except Exception as e:
self.add_result("Netlify", "Authentication", "ERROR", str(e))
def check_gcp_credentials(self):
"""Check Google Cloud credentials and connectivity with intelligent analysis"""
# Analyze application credentials
self.check_gcp_credentials_file()
# Test gcloud connectivity
if self.check_command_exists("gcloud", "GCP", "gcloud CLI"):
try:
result = subprocess.run(['gcloud', 'auth', 'list', '--format=json'],
capture_output=True, text=True, timeout=15)
if result.returncode == 0:
accounts = json.loads(result.stdout)
active_accounts = [acc for acc in accounts if acc.get('status') == 'ACTIVE']
if active_accounts:
account = active_accounts[0]['account']
self.add_result("GCP", "Authentication", "OK", f"Active: {account}")
else:
self.add_result("GCP", "Authentication", "WARNING", "No active accounts")
else:
self.add_result("GCP", "Authentication", "ERROR", result.stderr.strip())
except subprocess.TimeoutExpired:
self.add_result("GCP", "Authentication", "ERROR", "Request timeout")
except Exception as e:
self.add_result("GCP", "Authentication", "ERROR", str(e))
def check_digitalocean_credentials(self):
"""Check DigitalOcean credentials with smart detection"""
# Smart detection for doctl config
self.check_doctl_config_smart()
# Test doctl connectivity
if self.check_command_exists("doctl", "DigitalOcean", "doctl CLI"):
try:
result = subprocess.run(['doctl', 'account', 'get'],
capture_output=True, text=True, timeout=15)
if result.returncode == 0:
self.add_result("DigitalOcean", "API connectivity", "OK", "Account accessible")
else:
self.add_result("DigitalOcean", "API connectivity", "ERROR", result.stderr.strip())
except subprocess.TimeoutExpired:
self.add_result("DigitalOcean", "API connectivity", "ERROR", "Request timeout")
except Exception as e:
self.add_result("DigitalOcean", "API connectivity", "ERROR", str(e))
def check_ansible_config_smart(self):
"""Smart detection for Ansible configuration files"""
# Check project-local first (highest priority)
project_config_path = None
if self.project_path:
project_config_path = os.path.join(self.project_path, 'ansible.cfg')
if project_config_path and os.path.exists(project_config_path):
self.add_result("Ansible", "Config file", "OK", f"Project: {project_config_path}")
elif os.path.exists('./ansible.cfg'):
self.add_result("Ansible", "Config file", "OK", "Project: ./ansible.cfg")
# Check user home directory
elif os.path.exists(os.path.expanduser('~/.ansible.cfg')):
self.add_result("Ansible", "Config file", "OK", "User: ~/.ansible.cfg")
else:
self.add_result("Ansible", "Config file", "MISSING", "No project or user config found")
# Check system-wide config (separate check)
if os.path.exists('/etc/ansible/ansible.cfg'):
self.add_result("Ansible", "Global config", "OK", "System: /etc/ansible/ansible.cfg")
else:
self.add_result("Ansible", "Global config", "MISSING", "Path: /etc/ansible/ansible.cfg")
def check_doctl_config_smart(self):
"""Smart detection for DigitalOcean doctl configuration files"""
project_configs = [
'doctl.yaml',
'.doctl/config.yaml',
'config/doctl.yaml'
]
# Check for project-specific config first
project_found = False
search_paths = [self.project_path] if self.project_path else ['.']
for base_path in search_paths:
if project_found: break
for config_file in project_configs:
config_path = os.path.join(base_path, config_file)
if os.path.exists(config_path):
self.add_result("DigitalOcean", "Config file", "OK", f"Project: {config_path}")
project_found = True
break
# Check global config if no project config found
if not project_found:
global_config = os.path.expanduser('~/.config/doctl/config.yaml')
if os.path.exists(global_config):
self.add_result("DigitalOcean", "Config file", "OK", "Global: ~/.config/doctl/config.yaml")
else:
self.add_result("DigitalOcean", "Config file", "MISSING", "No project or global config found")
def check_ssh_config(self):
"""Check and parse SSH configuration"""
ssh_config_path = os.path.expanduser("~/.ssh/config")
if not os.path.exists(ssh_config_path):
self.add_result("SSH", "SSH config", "MISSING", f"Path: {ssh_config_path}")
return
try:
with open(ssh_config_path, 'r') as f:
content = f.read()
# Parse SSH config for key settings
lines = content.split('\n')
hosts = []
global_settings = {}
current_host = None
for line in lines:
line = line.strip()
if not line or line.startswith('#'):
continue
if line.lower().startswith('host '):
host_name = line.split(None, 1)[1]
if host_name != '*': # Skip global host patterns for counting
hosts.append(host_name)
current_host = host_name
elif current_host is None: # Global settings
if ' ' in line:
key, value = line.split(None, 1)
global_settings[key.lower()] = value
# Create simple summary - just host count
if hosts:
summary = f"Hosts: {len(hosts)}"
else:
summary = "No hosts configured"
self.add_result("SSH", "SSH config", "OK", summary)
except Exception as e:
self.add_result("SSH", "SSH config", "ERROR", f"Failed to parse: {str(e)}")
def check_ssh_known_hosts(self):
"""Check and parse SSH known hosts"""
known_hosts_path = os.path.expanduser("~/.ssh/known_hosts")
if not os.path.exists(known_hosts_path):
self.add_result("SSH", "Known hosts", "MISSING", f"Path: {known_hosts_path}")
return
try:
with open(known_hosts_path, 'r') as f:
lines = f.readlines()
# Parse known hosts
hosts = set()
key_types = {}
for line in lines:
line = line.strip()
if not line or line.startswith('#'):
continue
parts = line.split()
if len(parts) >= 3:
host_part = parts[0]
key_type = parts[1]
# Extract hostname (handle hashed hosts)
if host_part.startswith('|1|'):
hosts.add('[hashed]')
else:
# Handle comma-separated hosts and ports
for host in host_part.split(','):
# Remove port numbers and brackets
clean_host = host.split(':')[0].strip('[]')
if clean_host:
hosts.add(clean_host)
# Count key types
key_types[key_type] = key_types.get(key_type, 0) + 1
# Create simple summary - just entry count
non_empty_lines = [line for line in lines if line.strip() and not line.strip().startswith('#')]
summary = f"Entries: {len(non_empty_lines)}"
self.add_result("SSH", "Known hosts", "OK", summary)
except Exception as e:
self.add_result("SSH", "Known hosts", "ERROR", f"Failed to parse: {str(e)}")
def check_ssh_keys(self):
"""Check SSH keys in .ssh directory"""
ssh_dir = os.path.expanduser("~/.ssh")
if not os.path.exists(ssh_dir):
self.add_result("SSH Keys", "SSH directory", "MISSING", f"Path: {ssh_dir}")
return
if not os.access(ssh_dir, os.R_OK):
self.add_result("SSH Keys", "SSH directory", "WARNING", f"Permission denied: {ssh_dir}")
return
try:
found_keys = []
warnings = []
orphaned_keys = []
weak_keys = []
def scan_directory(directory, relative_path="", depth=0, max_depth=3):
"""Recursively scan directory for SSH keys with depth limit"""
if depth > max_depth:
return
try:
items = os.listdir(directory)
except PermissionError as e:
warnings.append(f"Permission denied: {relative_path or 'root'}")
return
for item in items:
if item.startswith('.'):
continue
item_path = os.path.join(directory, item)
item_relative = os.path.join(relative_path, item) if relative_path else item
if os.path.isfile(item_path):
# Check for public keys without private keys
if item.endswith('.pub'):
private_key_path = item_path[:-4] # Remove .pub extension
if not os.path.exists(private_key_path):
orphaned_keys.append(f"Public key without private: {item_relative}")
# Check if it's a potential private key (no .pub extension)
elif not item.endswith('.pub'):
pub_path = item_path + '.pub'
if os.path.exists(pub_path):
try:
# Try to determine key type by reading the public key
with open(pub_path, 'r') as f:
pub_content = f.read().strip()
key_type = "Unknown"
is_weak = False
if pub_content.startswith('ssh-rsa '):
key_type = "RSA"
# Check RSA key strength (basic heuristic)
parts = pub_content.split()
if len(parts) >= 2:
# RSA keys < 2048 bits are considered weak
# This is a rough estimate based on key length
key_data = parts[1]
if len(key_data) < 350: # Rough estimate for < 2048 bit
is_weak = True
weak_keys.append(f"{item_relative}: RSA key may be < 2048 bits")
elif pub_content.startswith('ssh-dss '):
key_type = "DSA"
is_weak = True
weak_keys.append(f"{item_relative}: DSA keys are deprecated")
elif pub_content.startswith('ecdsa-sha2-'):
key_type = "ECDSA"
elif pub_content.startswith('ssh-ed25519 '):
key_type = "ED25519"
found_keys.append({
'name': item,
'path': item_relative,
'directory': relative_path or ".",
'type': key_type,
'has_public': True,
'is_weak': is_weak
})
except Exception as e:
warnings.append(f"Could not read {item_relative}: {str(e)}")
else:
# Private key without public key
# Check if it looks like an SSH key by trying to read first few lines
try:
with open(item_path, 'r') as f:
first_line = f.readline().strip()
if 'BEGIN' in first_line and 'PRIVATE KEY' in first_line:
orphaned_keys.append(f"Private key without public: {item_relative}")
except:
pass # Not a readable key file
elif os.path.isdir(item_path) and depth < max_depth:
# Recursively scan subdirectory
scan_directory(item_path, item_relative, depth + 1, max_depth)
# Start scanning from the main .ssh directory
scan_directory(ssh_dir)
# Create summary
all_issues = []
if orphaned_keys:
all_issues.extend(orphaned_keys)
if weak_keys:
all_issues.extend(weak_keys)
if warnings:
all_issues.extend(warnings)
if found_keys:
key_types = [key['type'] for key in found_keys]
type_counts = {}
for kt in key_types:
type_counts[kt] = type_counts.get(kt, 0) + 1
summary_parts = [f"{count} {ktype}" for ktype, count in type_counts.items()]
summary = f"Found {len(found_keys)} keys: {', '.join(summary_parts)}"
# Determine status based on issues found
status = "OK"
if orphaned_keys or weak_keys:
status = "WARNING"
issue_count = len(orphaned_keys) + len(weak_keys)
summary += f" ({issue_count} issues)"
elif warnings:
status = "WARNING"
summary += f" ({len(warnings)} warnings)"
details = summary
if all_issues:
details += f"\nIssues: {'; '.join(all_issues)}"
self.add_result("SSH Keys", "SSH keys", status, details)
else:
if all_issues:
self.add_result("SSH Keys", "SSH keys", "WARNING", f"No valid key pairs found. Issues: {'; '.join(all_issues)}")
else:
self.add_result("SSH Keys", "SSH keys", "INFO", "No SSH key pairs found")
except Exception as e:
self.add_result("SSH Keys", "SSH keys", "ERROR", f"Failed to check SSH keys: {str(e)}")
def check_hosts_file(self):
"""Check /etc/hosts file and identify non-standard entries"""
hosts_path = "/etc/hosts"
if not os.path.exists(hosts_path):
self.add_result("System", "/etc/hosts", "MISSING", "File not found")
return
try:
with open(hosts_path, 'r') as f:
lines = f.readlines()
# Standard entries that are typically found in /etc/hosts
standard_entries = {
'127.0.0.1': ['localhost'],
'::1': ['localhost'],
'255.255.255.255': ['broadcasthost'],
'fe80::1%lo0': ['localhost']
}
custom_entries = []
total_entries = 0
for line in lines:
line = line.strip()
# Skip empty lines and comments
if not line or line.startswith('#'):
continue
# Parse the line
parts = line.split()
if len(parts) < 2:
continue
ip = parts[0]
hostnames = parts[1:]
total_entries += 1
# Check if this is a standard entry
is_standard = False
if ip in standard_entries:
# Check if hostnames match standard ones
expected_hostnames = standard_entries[ip]
if set(hostnames).issubset(set(expected_hostnames)):
is_standard = True
# If not standard, add to custom entries
if not is_standard:
custom_entries.append({
'ip': ip,
'hostnames': hostnames
})
# Create summary
if custom_entries:
custom_count = len(custom_entries)
if custom_count <= 5: # Show details if reasonable number
custom_list = []
for entry in custom_entries[:5]:
hostnames_str = ', '.join(entry['hostnames'])
custom_list.append(f"{entry['ip']} -> {hostnames_str}")
summary = f"Total: {total_entries}, Custom: {custom_count} ({'; '.join(custom_list)})"
else:
summary = f"Total: {total_entries}, Custom: {custom_count} entries"
self.add_result("System", "/etc/hosts", "WARNING", summary)
else:
summary = f"Total: {total_entries}, Standard entries only"
self.add_result("System", "/etc/hosts", "OK", summary)
# Store custom entries for detailed display
self.custom_hosts_entries = custom_entries
except PermissionError:
self.add_result("System", "/etc/hosts", "ERROR", "Permission denied")
except Exception as e:
self.add_result("System", "/etc/hosts", "ERROR", f"Failed to parse: {str(e)}")
def print_ssh_config_details(self):
"""Print detailed SSH configuration table"""
ssh_config_path = os.path.expanduser("~/.ssh/config")
if not os.path.exists(ssh_config_path):
return
try:
with open(ssh_config_path, 'r') as f:
content = f.read()
# Parse SSH config for detailed host information
lines = content.split('\n')
hosts_config = {}
current_host = None
global_settings = {}
for line in lines:
line = line.strip()
if not line or line.startswith('#'):
continue
if line.lower().startswith('host '):
current_host = line.split(None, 1)[1]
if current_host not in hosts_config:
hosts_config[current_host] = {}
elif current_host and ' ' in line:
key, value = line.split(None, 1)
hosts_config[current_host][key.lower()] = value
elif current_host is None and ' ' in line: # Global settings
key, value = line.split(None, 1)
global_settings[key.lower()] = value
if hosts_config:
print(f"\n{Colors.BOLD}🔧 SSH Configuration Details{Colors.END}")
print("=" * 100)
print(f"{Colors.BOLD}{'Host':<20} {'Hostname':<25} {'User':<15} {'Port':<8} {'Other Settings':<30}{Colors.END}")
print("-" * 100)
for host, config in hosts_config.items():
if host == '*': # Skip global patterns
continue
hostname = config.get('hostname', '')
user = config.get('user', '')
port = config.get('port', '22')
# Collect other interesting settings
other_settings = []
for key in ['identityfile', 'forwardagent', 'compression']:
if key in config:
value = config[key]
if key == 'identityfile':
value = value.split('/')[-1] # Just filename
other_settings.append(f"{key.title()}: {value}")
other_str = ', '.join(other_settings[:2]) # Limit to avoid overflow
if len(other_settings) > 2:
other_str += '...'
print(f"{host:<20} {hostname:<25} {user:<15} {port:<8} {other_str:<30}")
except Exception as e:
print(f"Error parsing SSH config: {e}")
def print_known_hosts_details(self):
"""Print detailed known hosts table"""
known_hosts_path = os.path.expanduser("~/.ssh/known_hosts")
if not os.path.exists(known_hosts_path):
return
try:
with open(known_hosts_path, 'r') as f:
lines = f.readlines()
# Parse known hosts for detailed information
host_entries = []
for line in lines:
line = line.strip()
if not line or line.startswith('#'):
continue
parts = line.split()
if len(parts) >= 3:
host_part = parts[0]
key_type = parts[1]
# Extract hostname (handle hashed hosts)
if host_part.startswith('|1|'):
display_host = '[hashed]'
else:
# Handle comma-separated hosts and ports
hosts = []
for host in host_part.split(','):
# Remove port numbers and brackets
clean_host = host.split(':')[0].strip('[]')
if clean_host:
hosts.append(clean_host)
display_host = ', '.join(hosts[:2]) # Show max 2 hosts
if len(hosts) > 2:
display_host += f' (+{len(hosts)-2} more)'
host_entries.append({
'host': display_host,
'key_type': key_type
})
if host_entries:
print(f"\n{Colors.BOLD}🔑 SSH Known Hosts Details{Colors.END}")
print("=" * 65)
print(f"{Colors.BOLD}{'Host/IP':<40} {'Key Type':<25}{Colors.END}")
print("-" * 65)
# Sort by host for better readability
host_entries.sort(key=lambda x: x['host'])
for entry in host_entries:
print(f"{entry['host']:<40} {entry['key_type']:<25}")
except Exception as e:
print(f"Error parsing known hosts: {e}")
def print_hosts_details(self):
"""Print detailed /etc/hosts custom entries table"""
if not hasattr(self, 'custom_hosts_entries') or not self.custom_hosts_entries:
return
print(f"\n{Colors.BOLD}🏠 /etc/hosts Custom Entries{Colors.END}")
print("=" * 70)
print(f"{Colors.BOLD}{'IP Address':<20} {'Hostnames':<50}{Colors.END}")
print("-" * 70)
for entry in self.custom_hosts_entries:
hostnames_str = ', '.join(entry['hostnames'])
# Truncate if too long
if len(hostnames_str) > 48:
hostnames_str = hostnames_str[:45] + '...'
print(f"{entry['ip']:<20} {hostnames_str:<50}")
def print_ssh_keys_details(self):
"""Print detailed SSH keys table grouped by directory"""
ssh_dir = os.path.expanduser("~/.ssh")
if not os.path.exists(ssh_dir) or not os.access(ssh_dir, os.R_OK):
return
try:
found_keys = []
def scan_directory(directory, relative_path="", depth=0, max_depth=3):
"""Recursively scan directory for SSH keys with depth limit"""
if depth > max_depth:
return
try:
items = os.listdir(directory)
except PermissionError:
return
for item in items:
if item.startswith('.'):
continue
item_path = os.path.join(directory, item)
item_relative = os.path.join(relative_path, item) if relative_path else item
if os.path.isfile(item_path):
# Check if it's a potential private key (no .pub extension)
if not item.endswith('.pub'):
pub_path = item_path + '.pub'
# Only include keys that have corresponding .pub files
if os.path.exists(pub_path):
try:
# Try to determine key type by reading the public key
with open(pub_path, 'r') as f:
pub_content = f.read().strip()
key_type = "Unknown"
key_details = ""
if pub_content.startswith('ssh-rsa '):
key_type = "RSA"
key_details = "RSA key"
elif pub_content.startswith('ssh-dss '):
key_type = "DSA"
key_details = "DSA key"
elif pub_content.startswith('ecdsa-sha2-'):
key_type = "ECDSA"
if 'nistp256' in pub_content:
key_details = "ECDSA 256-bit"
elif 'nistp384' in pub_content:
key_details = "ECDSA 384-bit"
elif 'nistp521' in pub_content:
key_details = "ECDSA 521-bit"
else:
key_details = "ECDSA key"
elif pub_content.startswith('ssh-ed25519 '):
key_type = "ED25519"
key_details = "ED25519 256-bit"
# Get file modification time for creation info
import time
mtime = os.path.getmtime(item_path)
created = time.strftime('%Y-%m-%d', time.localtime(mtime))
found_keys.append({
'name': item,
'path': item_relative,
'directory': relative_path or ".",
'type': key_type,
'details': key_details,
'created': created,
'has_public': True
})
except Exception:
# Skip problematic keys silently in details view
continue
elif os.path.isdir(item_path) and depth < max_depth:
# Recursively scan subdirectory
scan_directory(item_path, item_relative, depth + 1, max_depth)
# Start scanning from the main .ssh directory
scan_directory(ssh_dir)
if found_keys:
print(f"\n{Colors.BOLD}🔐 SSH Keys Details{Colors.END}")
print("=" * 110)
print(f"{Colors.BOLD}{'Directory':<20} {'Key Name':<25} {'Type':<15} {'Details':<20} {'Created':<15} {'Public':<10}{Colors.END}")
print("-" * 110)
# Group keys by directory and sort
from collections import defaultdict
keys_by_dir = defaultdict(list)
for key in found_keys:
keys_by_dir[key['directory']].append(key)
# Sort directories, with root (.) first
sorted_dirs = sorted(keys_by_dir.keys(), key=lambda x: (x != ".", x))
for directory in sorted_dirs:
dir_keys = sorted(keys_by_dir[directory], key=lambda x: x['name'])
for i, key in enumerate(dir_keys):
dir_display = directory if i == 0 else ""
public_status = "✅ Yes" if key['has_public'] else "❌ No"
print(f"{dir_display:<20} {key['name']:<25} {key['type']:<15} {key['details']:<20} {key['created']:<15} {public_status:<10}")
except Exception as e:
print(f"Error displaying SSH keys details: {e}")
def run_all_checks(self):
"""Run all environment checks"""