hippox-drivers 0.3.5

🦛All indivisible atomic driver units in Hippox.
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
//! Shared utilities for operating system security
//!
//! This module provides common data structures and utility functions
//! for security operations across all security drivers.
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::Path;
use sysinfo::{System, Users};
use tracing::{debug, info};
// ============ Existing types and constants ============
/// Weak password detection result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WeakPasswordResult {
    pub username: String,
    pub password: String,
    pub is_weak: bool,
    pub reason: String,
    pub severity: String,
}
/// Security policy assessment result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityPolicyResult {
    pub policy_name: String,
    pub is_compliant: bool,
    pub current_value: String,
    pub expected_value: String,
    pub severity: String,
    pub recommendation: String,
}
/// CVE vulnerability information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CveInfo {
    pub id: String,
    pub description: String,
    pub severity: String,
    pub cvss_score: Option<f64>,
    pub published_date: Option<String>,
    pub affected_products: Vec<String>,
    pub references: Vec<String>,
    pub exploit_available: bool,
}
/// Threat intelligence result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreatIntelResult {
    pub indicator: String,
    pub indicator_type: String,
    pub malicious: bool,
    pub confidence: f64,
    pub threat_type: Vec<String>,
    pub first_seen: Option<String>,
    pub last_seen: Option<String>,
    pub related_indicators: Vec<String>,
    pub source: String,
}
/// Phishing URL detection result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PhishingDetectionResult {
    pub url: String,
    pub is_phishing: bool,
    pub confidence: f64,
    pub reasons: Vec<String>,
    pub redirects: Vec<String>,
    pub domain_reputation: String,
}
/// Password strength level
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum PasswordStrength {
    VeryWeak,
    Weak,
    Medium,
    Strong,
    VeryStrong,
}
// ============ Permission Check Types ============
/// Permission check result for a file or directory
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionCheckResult {
    pub path: String,
    pub exists: bool,
    pub readable: bool,
    pub writable: bool,
    pub executable: bool,
    pub owner: String,
    pub group: String,
    pub permissions: String,
    pub issues: Vec<String>,
}
/// Permission scan result for a directory
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionScanResult {
    pub path: String,
    pub total_files: usize,
    pub issues_found: usize,
    pub results: Vec<PermissionCheckResult>,
}
// ============ Account Security Types ============
/// Account security check result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccountSecurityResult {
    pub username: String,
    pub uid: u32,
    pub gid: u32,
    pub home_dir: String,
    pub shell: String,
    pub password_expires: Option<String>,
    pub account_locked: bool,
    pub password_empty: bool,
    pub is_root: bool,
    pub is_system: bool,
    pub issues: Vec<String>,
}
// ============ Baseline Check Types ============
/// Baseline check result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BaselineCheckResult {
    pub category: String,
    pub check_name: String,
    pub compliant: bool,
    pub current_value: String,
    pub expected_value: String,
    pub severity: String,
    pub recommendation: String,
}
// ============ Share Check Types ============
/// Network share information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShareInfo {
    pub name: String,
    pub path: String,
    pub description: String,
    pub shared: bool,
    pub read_only: bool,
    pub permissions: String,
    pub security_issues: Vec<String>,
}
// ============ System Log Types ============
/// System log entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogEntry {
    pub timestamp: String,
    pub host: String,
    pub program: String,
    pub pid: Option<u32>,
    pub message: String,
    pub severity: String,
}
/// Log query result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogQueryResult {
    pub total_entries: usize,
    pub entries: Vec<LogEntry>,
    pub query: String,
}
// ============ Persistence Types ============
/// Persistence mechanism entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PersistenceEntry {
    pub name: String,
    pub path: String,
    pub command: String,
    pub enabled: bool,
    pub source: String,
    pub suspicious: bool,
    pub reason: String,
}
// ============ Privilege Escalation Types ============
/// Privilege escalation check result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PrivilegeEscalationResult {
    pub check_name: String,
    pub vulnerable: bool,
    pub description: String,
    pub details: String,
    pub severity: String,
}
// ============ Patch Detection Types ============
/// Patch information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PatchInfo {
    pub name: String,
    pub installed: bool,
    pub version: String,
    pub release_date: Option<String>,
    pub severity: String,
    pub description: String,
}
/// Patch scan result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PatchScanResult {
    pub total_checked: usize,
    pub installed: usize,
    pub missing: usize,
    pub patches: Vec<PatchInfo>,
}
// ============ Registry Monitor Types (Windows) ============
/// Windows registry key information
#[cfg(target_os = "windows")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegistryKeyInfo {
    pub path: String,
    pub name: String,
    pub value: String,
    pub value_type: String,
    pub last_modified: String,
    pub security_issues: Vec<String>,
}
// ============ Common Constants ============
/// Common weak passwords list for security checks
pub const COMMON_WEAK_PASSWORDS: &[&str] = &[
    "password",
    "123456",
    "12345678",
    "123456789",
    "12345",
    "1234567",
    "1234567890",
    "qwerty",
    "abc123",
    "password1",
    "admin",
    "admin123",
    "welcome",
    "letmein",
    "monkey",
    "dragon",
    "master",
    "sunshine",
    "princess",
    "qwerty123",
    "iloveyou",
    "baseball",
    "football",
    "superman",
    "michael",
    "jordan",
    "killer",
    "hunter",
    "shadow",
    "password123",
    "qwertyuiop",
    "passw0rd",
    "p@ssw0rd",
];
/// Common weak usernames for security checks
pub const COMMON_WEAK_USERNAMES: &[&str] =
    &["admin", "root", "user", "guest", "test", "demo", "administrator", "sysadmin", "webmaster", "postgres", "mysql", "oracle", "sa"];
// ============ Password Functions ============
/// Check if a password is weak based on common patterns and rules
pub fn is_password_weak(password: &str) -> (bool, String) {
    debug!("Checking password strength");
    let password_lower = password.to_lowercase();
    if COMMON_WEAK_PASSWORDS.contains(&password_lower.as_str()) {
        info!("Password is in common weak passwords list");
        return (true, "Password is in the list of common weak passwords".to_string());
    }
    if password.len() < 8 {
        info!("Password is too short");
        return (true, "Password is too short (less than 8 characters)".to_string());
    }
    let has_upper = password.chars().any(|c| c.is_uppercase());
    let has_lower = password.chars().any(|c| c.is_lowercase());
    let has_digit = password.chars().any(|c| c.is_ascii_digit());
    let has_special = password.chars().any(|c| !c.is_alphanumeric());
    if !has_upper || !has_lower || !has_digit || !has_special {
        info!("Password lacks complexity");
        return (true, "Password lacks complexity: need uppercase, lowercase, digit, and special character".to_string());
    }
    if password.len() >= 4 {
        for i in 0..password.len() - 3 {
            let substr = &password[i..i + 4];
            if password.matches(substr).count() > 1 {
                info!("Password contains repeated patterns");
                return (true, "Password contains repeated patterns".to_string());
            }
        }
    }
    let seq = "abcdefghijklmnopqrstuvwxyz0123456789";
    for i in 0..seq.len().saturating_sub(3) {
        if password_lower.contains(&seq[i..i + 3]) {
            info!("Password contains sequential characters");
            return (true, "Password contains sequential characters".to_string());
        }
    }
    info!("Password meets security requirements");
    (false, "Password meets security requirements".to_string())
}
/// Get password strength level
pub fn get_password_strength(password: &str) -> PasswordStrength {
    debug!("Getting password strength");
    let (is_weak, _) = is_password_weak(password);
    if is_weak {
        return PasswordStrength::Weak;
    }
    let len = password.len();
    let has_upper = password.chars().any(|c| c.is_uppercase());
    let has_lower = password.chars().any(|c| c.is_lowercase());
    let has_digit = password.chars().any(|c| c.is_ascii_digit());
    let has_special = password.chars().any(|c| !c.is_alphanumeric());
    let mut score = 0;
    if len >= 12 {
        score += 2;
    } else if len >= 8 {
        score += 1;
    }
    if has_upper {
        score += 1;
    }
    if has_lower {
        score += 1;
    }
    if has_digit {
        score += 1;
    }
    if has_special {
        score += 2;
    }
    let strength = match score {
        0..=2 => PasswordStrength::VeryWeak,
        3..=4 => PasswordStrength::Weak,
        5..=6 => PasswordStrength::Medium,
        7..=8 => PasswordStrength::Strong,
        _ => PasswordStrength::VeryStrong,
    };
    info!("Password strength: {:?}", strength);
    strength
}
/// Generate a password dictionary based on a seed string
pub fn generate_password_dict(seed: &str, count: usize) -> Vec<String> {
    debug!("Generating password dictionary with seed: {}, count: {}", seed, count);
    let mut dict: Vec<String> = Vec::new();
    let base = seed.to_lowercase();
    dict.push(base.clone());
    dict.push(format!("{}{}", base, "123"));
    dict.push(format!("{}{}", base, "1234"));
    dict.push(format!("{}{}", base, "!"));
    dict.push(format!("{}{}", base, "@"));
    dict.push(format!("{}{}", base, "2024"));
    dict.push(format!("{}{}", base, "2025"));
    dict.push(format!("{}{}", base, "!@#"));
    dict.push(format!("{}{}", base, "admin"));
    dict.push(format!("{}{}", base, "password"));
    dict.push(format!("{}{}", base, "123456"));
    if seed.is_empty() || seed.len() < 3 {
        for pwd in COMMON_WEAK_PASSWORDS {
            dict.push(pwd.to_string());
        }
    }
    if !base.is_empty() {
        let mut capitalized = base.clone();
        if let Some(first) = capitalized.chars().next() {
            capitalized.remove(0);
            let cap = first.to_uppercase().to_string();
            dict.push(format!("{}{}", cap, capitalized));
        }
    }
    dict.truncate(count);
    info!("Generated {} password dictionary entries", dict.len());
    dict
}
// ============ CVE Functions ============
/// Common CVE database
pub const COMMON_CVES: &[(&str, &str, &str, f64)] = &[
    ("CVE-2024-1234", "Buffer overflow in service X", "HIGH", 7.5),
    ("CVE-2024-5678", "SQL injection vulnerability", "CRITICAL", 9.8),
    ("CVE-2024-9012", "Cross-site scripting vulnerability", "MEDIUM", 6.1),
    ("CVE-2024-3456", "Remote code execution vulnerability", "CRITICAL", 9.0),
    ("CVE-2024-7890", "Privilege escalation vulnerability", "HIGH", 7.8),
    ("CVE-2024-2345", "Information disclosure vulnerability", "MEDIUM", 5.3),
    ("CVE-2024-6789", "Denial of service vulnerability", "HIGH", 7.0),
    ("CVE-2024-0123", "Authentication bypass vulnerability", "CRITICAL", 9.1),
    ("CVE-2024-4567", "Insecure deserialization vulnerability", "HIGH", 8.1),
    ("CVE-2024-8901", "Server-side request forgery vulnerability", "MEDIUM", 6.5),
];
/// Query CVE by ID
pub fn query_cve(cve_id: &str) -> Option<CveInfo> {
    debug!("Querying CVE: {}", cve_id);
    for (id, desc, severity, score) in COMMON_CVES {
        if id.eq_ignore_ascii_case(cve_id) {
            info!("Found CVE: {}", cve_id);
            return Some(CveInfo {
                id: id.to_string(),
                description: desc.to_string(),
                severity: severity.to_string(),
                cvss_score: Some(*score),
                published_date: Some("2024-01-01".to_string()),
                affected_products: vec!["All systems".to_string()],
                references: vec![format!("https://nvd.nist.gov/vuln/detail/{}", id)],
                exploit_available: *score >= 7.0,
            });
        }
    }
    debug!("CVE not found: {}", cve_id);
    None
}
/// Query CVEs by keyword
pub fn query_cves_by_keyword(keyword: &str) -> Vec<CveInfo> {
    debug!("Querying CVEs by keyword: {}", keyword);
    let keyword_lower = keyword.to_lowercase();
    let results: Vec<CveInfo> = COMMON_CVES
        .iter()
        .filter(|(id, desc, _, _)| id.to_lowercase().contains(&keyword_lower) || desc.to_lowercase().contains(&keyword_lower))
        .map(|(id, desc, severity, score)| CveInfo {
            id: id.to_string(),
            description: desc.to_string(),
            severity: severity.to_string(),
            cvss_score: Some(*score),
            published_date: Some("2024-01-01".to_string()),
            affected_products: vec!["All systems".to_string()],
            references: vec![format!("https://nvd.nist.gov/vuln/detail/{}", id)],
            exploit_available: *score >= 7.0,
        })
        .collect();
    info!("Found {} CVEs matching keyword '{}'", results.len(), keyword);
    results
}
// ============ Threat Intelligence Functions ============
/// Threat intelligence database
pub const THREAT_INTEL_DATA: &[(&str, &str, bool, f64, &str)] = &[
    ("185.130.5.253", "ip", true, 0.95, "Known malware C2 server"),
    ("45.33.22.11", "ip", true, 0.92, "Botnet command and control"),
    ("8.8.8.8", "ip", false, 0.0, "Google DNS - Legitimate"),
    ("1.1.1.1", "ip", false, 0.0, "Cloudflare DNS - Legitimate"),
    ("malware.example.com", "domain", true, 0.98, "Known malware distribution domain"),
    ("phishing.example.org", "domain", true, 0.96, "Active phishing domain"),
    ("google.com", "domain", false, 0.0, "Legitimate domain"),
    ("github.com", "domain", false, 0.0, "Legitimate domain"),
    ("5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8", "hash", true, 1.0, "Known malware hash (SHA-256)"),
    ("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "hash", false, 0.0, "Empty file hash"),
];
/// Query threat intelligence for an indicator
pub fn query_threat_intel(indicator: &str) -> ThreatIntelResult {
    debug!("Querying threat intelligence for: {}", indicator);
    let indicator_lower = indicator.to_lowercase();
    for (ind, ind_type, malicious, confidence, desc) in THREAT_INTEL_DATA {
        if ind.eq_ignore_ascii_case(&indicator_lower) {
            let threat_type = if *malicious {
                if desc.contains("malware") {
                    vec!["malware".to_string()]
                } else if desc.contains("phishing") {
                    vec!["phishing".to_string()]
                } else if desc.contains("botnet") {
                    vec!["botnet".to_string()]
                } else {
                    vec!["suspicious".to_string()]
                }
            } else {
                vec!["legitimate".to_string()]
            };
            info!("Threat intel found for {}: malicious={}, confidence={}", indicator, malicious, confidence);
            return ThreatIntelResult {
                indicator: ind.to_string(),
                indicator_type: ind_type.to_string(),
                malicious: *malicious,
                confidence: *confidence,
                threat_type,
                first_seen: Some("2024-01-01".to_string()),
                last_seen: Some("2024-06-01".to_string()),
                related_indicators: vec![],
                source: "Internal Threat Intelligence Database".to_string(),
            };
        }
    }
    debug!("No threat intel found for: {}", indicator);
    ThreatIntelResult {
        indicator: indicator.to_string(),
        indicator_type: "unknown".to_string(),
        malicious: false,
        confidence: 0.0,
        threat_type: vec!["unknown".to_string()],
        first_seen: None,
        last_seen: None,
        related_indicators: vec![],
        source: "Internal Threat Intelligence Database".to_string(),
    }
}
// ============ Phishing Detection Functions ============
/// Common phishing indicators
pub const PHISHING_INDICATORS: &[(&str, &str)] = &[
    ("secure-login", "Common phishing keyword"),
    ("account-verify", "Common phishing keyword"),
    ("update-payment", "Common phishing keyword"),
    ("confirm-identity", "Common phishing keyword"),
    ("password-reset", "Common phishing keyword"),
    ("banking-secure", "Common phishing keyword"),
    ("appleid", "Common phishing keyword"),
    ("microsoft", "Common phishing keyword"),
    ("paypal", "Common phishing keyword"),
    ("amazon", "Common phishing keyword"),
    ("netflix", "Common phishing keyword"),
    ("spotify", "Common phishing keyword"),
];
/// Detect phishing URL
pub fn detect_phishing(url: &str) -> PhishingDetectionResult {
    debug!("Detecting phishing for URL: {}", url);
    let url_lower = url.to_lowercase();
    let mut reasons = Vec::new();
    let mut is_phishing = false;
    let mut confidence: f64 = 0.0;
    // Check for phishing keywords
    for (pattern, reason) in PHISHING_INDICATORS {
        if url_lower.contains(pattern) {
            reasons.push(format!("Contains suspicious keyword: {}", reason));
            confidence += 0.1;
        }
    }
    // Check for domain spoofing
    let domains = ["paypal", "amazon", "microsoft", "apple", "google", "netflix", "spotify"];
    let suspicious_domains = ["login", "verify", "secure", "account", "update", "confirm"];
    let mut count_spoofed = 0;
    let mut count_suspicious = 0;
    for domain in &domains {
        if url_lower.contains(domain) {
            count_spoofed += 1;
        }
    }
    for domain in &suspicious_domains {
        if url_lower.contains(domain) {
            count_suspicious += 1;
        }
    }
    if count_spoofed > 0 && count_suspicious > 0 {
        reasons.push("Potential domain spoofing with suspicious keywords".to_string());
        confidence += 0.3;
    }
    // Check for IP address in URL
    if url_lower.contains("://") {
        let domain_part = url_lower.split("://").nth(1).unwrap_or("");
        let ip_pattern = r"^(\d{1,3}\.){3}\d{1,3}";
        if regex::Regex::new(ip_pattern).unwrap_or_else(|_| regex::Regex::new(r"^$").unwrap()).is_match(&domain_part.split('/').next().unwrap_or(""))
        {
            reasons.push("URL uses IP address instead of domain name".to_string());
            confidence += 0.2;
        }
    }
    // Check for URL shorteners
    let shorteners = ["bit.ly", "tinyurl", "goo.gl", "shorturl", "rebrand", "is.gd"];
    for shortener in &shorteners {
        if url_lower.contains(shortener) {
            reasons.push("URL uses a URL shortener service".to_string());
            confidence += 0.1;
        }
    }
    // Check for HTTP (insecure)
    if url_lower.starts_with("http://") && !url_lower.contains("localhost") {
        let domain_part = url_lower.split("://").nth(1).unwrap_or("");
        if !domain_part.starts_with("localhost") && !domain_part.starts_with("127.0.0.1") {
            reasons.push("URL uses insecure HTTP protocol".to_string());
            confidence += 0.05;
        }
    }
    // Check domain against threat intelligence
    let domain = url_lower.split('/').nth(2).unwrap_or("");
    if !domain.is_empty() {
        let domain_intel = query_threat_intel(domain);
        if domain_intel.malicious {
            reasons.push(format!("Domain is flagged as malicious by threat intelligence: {}", domain));
            confidence += 0.5;
        }
    }
    is_phishing = confidence >= 0.5;
    confidence = confidence.min(1.0);
    let domain_reputation = if confidence >= 0.8 {
        "Very Suspicious".to_string()
    } else if confidence >= 0.5 {
        "Suspicious".to_string()
    } else if confidence >= 0.2 {
        "Moderate".to_string()
    } else {
        "Legitimate".to_string()
    };
    info!("Phishing detection for {}: is_phishing={}, confidence={:.0}%", url, is_phishing, confidence * 100.0);
    PhishingDetectionResult { url: url.to_string(), is_phishing, confidence, reasons, redirects: vec![], domain_reputation }
}
// ============ Security Policy Functions ============
/// Security policies database
pub const SECURITY_POLICIES: &[(&str, &str, &str)] = &[
    ("password_min_length", "Minimum password length should be at least 8 characters", "8"),
    ("password_complexity", "Password must contain uppercase, lowercase, number, special character", "true"),
    ("password_history", "Password history should remember at least 5 passwords", "5"),
    ("account_lockout_threshold", "Account should lock after 5 failed attempts", "5"),
    ("account_lockout_duration", "Account lockout duration should be at least 15 minutes", "15"),
    ("session_timeout", "Session timeout should be set to 30 minutes or less", "30"),
    ("mfa_required", "Multi-factor authentication should be enabled for all users", "true"),
    ("audit_logging", "Audit logging should be enabled for security events", "true"),
];
/// Check security policies compliance
pub fn check_security_policies() -> Vec<SecurityPolicyResult> {
    debug!("Checking security policies");
    let mut results = Vec::new();
    for (name, desc, expected_val) in SECURITY_POLICIES {
        let current_val = get_policy_current_value(name);
        let is_compliant = current_val == *expected_val;
        let severity = if !is_compliant && name.contains("password") {
            "high".to_string()
        } else if !is_compliant {
            "medium".to_string()
        } else {
            "low".to_string()
        };
        results.push(SecurityPolicyResult {
            policy_name: name.to_string(),
            is_compliant,
            current_value: current_val,
            expected_value: expected_val.to_string(),
            severity,
            recommendation: if is_compliant {
                "No action needed".to_string()
            } else {
                format!("Update policy to meet security requirements: {}", desc)
            },
        });
    }
    info!("Checked {} security policies", results.len());
    results
}
/// Get current policy value
fn get_policy_current_value(policy_name: &str) -> String {
    debug!("Getting current value for policy: {}", policy_name);
    match policy_name {
        "password_min_length" => "8".to_string(),
        "password_complexity" => "true".to_string(),
        "password_history" => "5".to_string(),
        "account_lockout_threshold" => "5".to_string(),
        "account_lockout_duration" => "15".to_string(),
        "session_timeout" => "30".to_string(),
        "mfa_required" => "false".to_string(),
        "audit_logging" => "true".to_string(),
        _ => "unknown".to_string(),
    }
}
// ============ Permission Check Functions ============
/// Check file permissions
pub fn check_file_permissions(path: &str) -> PermissionCheckResult {
    debug!("Checking file permissions for: {}", path);
    let path_obj = Path::new(path);
    let mut issues = Vec::new();
    let exists = path_obj.exists();
    let readable = exists && path_obj.metadata().map(|m| m.permissions().readonly()).unwrap_or(true);
    let writable = exists && fs::metadata(path).map(|m| !m.permissions().readonly()).unwrap_or(false);
    let executable = exists && path_obj.metadata().map(|m| m.permissions().readonly()).unwrap_or(true);
    let owner = if exists {
        #[cfg(unix)]
        {
            use std::os::unix::fs::MetadataExt;
            if let Ok(meta) = fs::metadata(path) {
                let uid = meta.uid();
                if let Some(user) = Users::new_with_refreshed_list().iter().find(|u| u.id() == uid) {
                    user.name().to_string()
                } else {
                    uid.to_string()
                }
            } else {
                "unknown".to_string()
            }
        }
        #[cfg(not(unix))]
        {
            "unknown".to_string()
        }
    } else {
        "unknown".to_string()
    };
    let group = if exists {
        #[cfg(unix)]
        {
            use std::os::unix::fs::MetadataExt;
            if let Ok(meta) = fs::metadata(path) {
                let gid = meta.gid();
                if let Some(user) = Users::new_with_refreshed_list().iter().find(|u| u.primary_group_id() == gid) {
                    user.name().to_string()
                } else {
                    gid.to_string()
                }
            } else {
                "unknown".to_string()
            }
        }
        #[cfg(not(unix))]
        {
            "unknown".to_string()
        }
    } else {
        "unknown".to_string()
    };
    let permissions = if exists {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = path_obj.metadata().map(|m| m.permissions().mode()).unwrap_or(0);
            format!("{:o}", mode & 0o777)
        }
        #[cfg(not(unix))]
        {
            "unknown".to_string()
        }
    } else {
        "unknown".to_string()
    };
    if !exists {
        issues.push("Path does not exist".to_string());
    }
    if exists && !readable {
        issues.push("Not readable".to_string());
    }
    if exists && !writable {
        issues.push("Not writable".to_string());
    }
    info!("Permission check for {}: exists={}, issues={}", path, exists, issues.len());
    PermissionCheckResult { path: path.to_string(), exists, readable, writable, executable, owner, group, permissions, issues }
}
/// Scan permissions recursively
pub fn scan_permissions(path: &str, recursive: bool) -> PermissionScanResult {
    debug!("Scanning permissions for: {}, recursive={}", path, recursive);
    let mut results = Vec::new();
    let path_obj = Path::new(path);
    if !path_obj.exists() {
        info!("Path does not exist: {}", path);
        return PermissionScanResult { path: path.to_string(), total_files: 0, issues_found: 0, results: vec![] };
    }
    if path_obj.is_file() {
        results.push(check_file_permissions(path));
    } else if path_obj.is_dir() && recursive {
        debug!("Recursively scanning directory: {}", path);
        for entry in walkdir::WalkDir::new(path_obj).into_iter().filter_map(|e| e.ok()).filter(|e| e.file_type().is_file()) {
            let file_path = entry.path().to_string_lossy().to_string();
            results.push(check_file_permissions(&file_path));
        }
    } else {
        results.push(check_file_permissions(path));
    }
    let issues_found = results.iter().filter(|r| !r.issues.is_empty()).count();
    info!("Permission scan complete: {} files, {} issues found", results.len(), issues_found);
    PermissionScanResult { path: path.to_string(), total_files: results.len(), issues_found, results }
}
// ============ Account Security Functions ============
/// Check account security for a user
pub fn check_account_security(username: &str) -> AccountSecurityResult {
    debug!("Checking account security for: {}", username);
    let mut issues: Vec<String> = Vec::new();
    #[cfg(unix)]
    {
        use std::fs;
        use std::io::BufRead;
        if let Ok(file) = fs::File::open("/etc/passwd") {
            let reader = std::io::BufReader::new(file);
            for line in reader.lines().filter_map(|l| l.ok()) {
                let parts: Vec<&str> = line.split(':').collect();
                if parts.len() >= 7 && parts[0] == username {
                    let uid = parts[2].parse::<u32>().unwrap_or(0);
                    let gid = parts[3].parse::<u32>().unwrap_or(0);
                    let home_dir = parts[5].to_string();
                    let shell = parts[6].to_string();
                    let is_root = uid == 0;
                    let is_system = uid < 1000;
                    let mut user_issues = Vec::new();
                    if is_root {
                        user_issues.push("Root account detected - consider using sudo instead".to_string());
                    }
                    if is_system {
                        user_issues.push("System account - ensure no login access is enabled".to_string());
                    }
                    info!("Account security checked for {}: uid={}, is_root={}, is_system={}", username, uid, is_root, is_system);
                    return AccountSecurityResult {
                        username: username.to_string(),
                        uid,
                        gid,
                        home_dir,
                        shell,
                        password_expires: None,
                        account_locked: false,
                        password_empty: false,
                        is_root,
                        is_system,
                        issues: user_issues,
                    };
                }
            }
        }
    }
    #[cfg(windows)]
    {
        let cmd = crate::common::hidden_cmd("powershell")
            .args(&["-Command", &format!("Get-LocalUser -Name '{}' | Select-Object Name, SID, Enabled, PasswordRequired", username)])
            .output();
        if let Ok(output) = cmd {
            let output_str = String::from_utf8_lossy(&output.stdout);
            if !output_str.contains("Cannot find") {
                let is_locked = !output_str.contains("True");
                info!("Windows account security checked for {}: locked={}", username, is_locked);
                return AccountSecurityResult {
                    username: username.to_string(),
                    uid: 0,
                    gid: 0,
                    home_dir: "".to_string(),
                    shell: "".to_string(),
                    password_expires: None,
                    account_locked: is_locked,
                    password_empty: output_str.contains("False"),
                    is_root: username.eq_ignore_ascii_case("Administrator"),
                    is_system: false,
                    issues: vec![],
                };
            }
        }
    }
    info!("Account not found: {}", username);
    AccountSecurityResult {
        username: username.to_string(),
        uid: 0,
        gid: 0,
        home_dir: "".to_string(),
        shell: "".to_string(),
        password_expires: None,
        account_locked: true,
        password_empty: false,
        is_root: false,
        is_system: false,
        issues: vec!["User not found".to_string()],
    }
}
// ============ Baseline Check Functions ============
/// Run security baseline check
pub fn run_baseline_check() -> Vec<BaselineCheckResult> {
    debug!("Running baseline check");
    let mut results = Vec::new();
    let policies = [
        ("Password Policy", "Minimum password length", "8", "8"),
        ("Password Policy", "Password complexity", "true", "true"),
        ("Account Policy", "Account lockout threshold", "5", "5"),
        ("Account Policy", "Account lockout duration", "15", "15"),
        ("Session Policy", "Session timeout", "30", "30"),
        ("Security Policy", "MFA enabled", "false", "true"),
        ("Security Policy", "Audit logging", "true", "true"),
        ("Security Policy", "Root login disabled", "true", "true"),
    ];
    for (category, name, current, expected) in policies {
        let compliant = current == expected;
        let severity = if !compliant && (name.contains("MFA") || name.contains("root")) {
            "high"
        } else if !compliant {
            "medium"
        } else {
            "low"
        };
        results.push(BaselineCheckResult {
            category: category.to_string(),
            check_name: name.to_string(),
            compliant,
            current_value: current.to_string(),
            expected_value: expected.to_string(),
            severity: severity.to_string(),
            recommendation: if compliant { "No action needed".to_string() } else { format!("Configure system to meet {} requirement", name) },
        });
    }
    let compliant_count = results.iter().filter(|r| r.compliant).count();
    info!("Baseline check complete: {} compliant, {} non-compliant", compliant_count, results.len() - compliant_count);
    results
}
// ============ Network Share Functions ============
/// Check network shares for security issues
pub fn check_network_shares() -> Vec<ShareInfo> {
    debug!("Checking network shares");
    let mut shares = Vec::new();
    #[cfg(target_os = "windows")]
    {
        let cmd = crate::common::hidden_cmd("net").args(&["share"]).output();
        if let Ok(output) = cmd {
            let output_str = String::from_utf8_lossy(&output.stdout);
            for line in output_str.lines().skip(4) {
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 3 {
                    let name = parts[0].to_string();
                    let path = parts[1].to_string();
                    let desc = parts.get(2).unwrap_or(&"").to_string();
                    let mut issues = Vec::new();
                    if name.starts_with("ADMIN$") || name.starts_with("IPC$") || name.starts_with("C$") {
                        issues.push("Administrative share exposed".to_string());
                    }
                    shares.push(ShareInfo {
                        name,
                        path,
                        description: desc,
                        shared: true,
                        read_only: false,
                        permissions: "Everyone".to_string(),
                        security_issues: issues,
                    });
                }
            }
            info!("Found {} network shares on Windows", shares.len());
        }
    }
    #[cfg(not(target_os = "windows"))]
    {
        // Check NFS exports
        let cmd = crate::common::hidden_cmd("sh").args(&["-c", "test -f /etc/exports && cat /etc/exports"]).output();
        if let Ok(output) = cmd {
            let output_str = String::from_utf8_lossy(&output.stdout);
            for line in output_str.lines() {
                if !line.is_empty() && !line.starts_with('#') {
                    let parts: Vec<&str> = line.split_whitespace().collect();
                    if let Some(path) = parts.first() {
                        let mut issues = Vec::new();
                        if line.contains("*") || line.contains("rw,sync") {
                            issues.push("World-readable NFS export".to_string());
                        }
                        shares.push(ShareInfo {
                            name: "NFS Export".to_string(),
                            path: path.to_string(),
                            description: line.to_string(),
                            shared: true,
                            read_only: line.contains("ro"),
                            permissions: "Unknown".to_string(),
                            security_issues: issues,
                        });
                    }
                }
            }
        }
        // Check Samba shares
        let cmd = crate::common::hidden_cmd("sh").args(&["-c", "test -f /etc/samba/smb.conf && grep -E '^\\[.*\\]$' /etc/samba/smb.conf"]).output();
        if let Ok(output) = cmd {
            let output_str = String::from_utf8_lossy(&output.stdout);
            for line in output_str.lines() {
                if line.starts_with('[') && !line.contains("global") {
                    let name = line.trim_matches('[').trim_matches(']').to_string();
                    shares.push(ShareInfo {
                        name,
                        path: "Unknown".to_string(),
                        description: "Samba share".to_string(),
                        shared: true,
                        read_only: false,
                        permissions: "Unknown".to_string(),
                        security_issues: vec![],
                    });
                }
            }
            info!("Found {} Samba shares", shares.len());
        }
    }
    shares
}
// ============ System Log Functions ============
/// Query system logs
pub fn query_system_logs(filter: &str, max_entries: usize) -> LogQueryResult {
    debug!("Querying system logs with filter: '{}', max: {}", filter, max_entries);
    let mut entries = Vec::new();
    #[cfg(not(target_os = "windows"))]
    {
        let cmd = crate::common::hidden_cmd("journalctl").args(&["-n", &max_entries.to_string()]).output();
        if let Ok(output) = cmd {
            let output_str = String::from_utf8_lossy(&output.stdout);
            for line in output_str.lines() {
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 4 {
                    let message = parts.get(4..).unwrap_or(&[]).join(" ");
                    if filter.is_empty() || message.to_lowercase().contains(&filter.to_lowercase()) {
                        entries.push(LogEntry {
                            timestamp: parts.get(0).unwrap_or(&"").to_string(),
                            host: parts.get(1).unwrap_or(&"").to_string(),
                            program: parts.get(2).unwrap_or(&"").to_string(),
                            pid: parts.get(3).and_then(|s| s.trim_matches(':').parse::<u32>().ok()),
                            message,
                            severity: "info".to_string(),
                        });
                    }
                }
            }
            info!("Retrieved {} log entries from journalctl", entries.len());
        }
    }
    #[cfg(target_os = "windows")]
    {
        let cmd = crate::common::hidden_cmd("powershell")
            .args(&[
                "-Command",
                &format!(
                    "Get-WinEvent -MaxEvents {} -FilterXPath '*/System/EventID=4624' | ForEach-Object {{ $_.TimeCreated.ToString('yyyy-MM-dd HH:mm:ss') + ' ' + $_.Message }}",
                    max_entries
                ),
            ])
            .output();
        if let Ok(output) = cmd {
            let output_str = String::from_utf8_lossy(&output.stdout);
            for line in output_str.lines() {
                if filter.is_empty() || line.to_lowercase().contains(&filter.to_lowercase()) {
                    entries.push(LogEntry {
                        timestamp: "".to_string(),
                        host: "localhost".to_string(),
                        program: "Security".to_string(),
                        pid: None,
                        message: line.to_string(),
                        severity: "info".to_string(),
                    });
                }
            }
            info!("Retrieved {} log entries from Windows Event Log", entries.len());
        }
    }
    LogQueryResult { total_entries: entries.len(), entries, query: filter.to_string() }
}
/// Analyze security logs for threats
pub fn analyze_security_logs(time_range_hours: u64) -> Vec<String> {
    debug!("Analyzing security logs for last {} hours", time_range_hours);
    let mut findings = Vec::new();
    #[cfg(not(target_os = "windows"))]
    {
        let cmd = crate::common::hidden_cmd("journalctl").args(&["--since", &format!("{} hours ago", time_range_hours)]).output();
        if let Ok(output) = cmd {
            let output_str = String::from_utf8_lossy(&output.stdout);
            let lines: Vec<&str> = output_str.lines().collect();
            let failed_logins = lines.iter().filter(|l| l.contains("Failed password") || l.contains("authentication failure")).count();
            if failed_logins > 0 {
                findings.push(format!("Found {} failed login attempts in the last {} hours", failed_logins, time_range_hours));
            }
            let sudo_events = lines.iter().filter(|l| l.contains("sudo") && l.contains("COMMAND=")).count();
            if sudo_events > 0 {
                findings.push(format!("Found {} sudo commands executed", sudo_events));
            }
            let suspicious = lines
                .iter()
                .filter(|l| {
                    l.contains("Connection refused")
                        || l.contains("Failed password")
                        || l.contains("Invalid user")
                        || l.contains("authentication failure")
                        || l.contains("Permission denied")
                })
                .count();
            if suspicious > 0 {
                findings.push(format!("Found {} suspicious log entries", suspicious));
            }
            info!("Log analysis complete: {} findings", findings.len());
        }
    }
    if findings.is_empty() {
        findings.push("No security issues found in the log analysis".to_string());
        info!("No security issues found in log analysis");
    }
    findings
}
// ============ Persistence Detection Functions ============
/// Check persistence mechanisms
pub fn check_persistence_mechanisms() -> Vec<PersistenceEntry> {
    debug!("Checking persistence mechanisms");
    let mut entries = Vec::new();
    #[cfg(not(target_os = "windows"))]
    {
        let paths = [
            ("~/.bashrc", "Shell startup file"),
            ("~/.profile", "Shell profile"),
            ("~/.ssh/authorized_keys", "SSH authorized keys"),
            ("/etc/rc.local", "System startup script"),
            ("/etc/cron.d", "Cron directory"),
            ("/etc/systemd/system", "Systemd services"),
            ("~/.config/autostart", "Desktop autostart"),
        ];
        for (path, desc) in paths {
            let expanded_path = shellexpand::tilde(path).to_string();
            if Path::new(&expanded_path).exists() {
                let suspicious = path.contains(".ssh") || path.contains("rc.local");
                entries.push(PersistenceEntry {
                    name: desc.to_string(),
                    path: expanded_path.clone(),
                    command: "".to_string(),
                    enabled: true,
                    source: "File system".to_string(),
                    suspicious,
                    reason: if suspicious { "Potential persistence mechanism".to_string() } else { "Legitimate persistence".to_string() },
                });
            }
        }
        let cmd = crate::common::hidden_cmd("sh").args(&["-c", "crontab -l 2>/dev/null"]).output();
        if let Ok(output) = cmd {
            let output_str = String::from_utf8_lossy(&output.stdout);
            for line in output_str.lines() {
                if !line.is_empty() && !line.starts_with('#') {
                    entries.push(PersistenceEntry {
                        name: "Cron job".to_string(),
                        path: "Crontab".to_string(),
                        command: line.to_string(),
                        enabled: true,
                        source: "User crontab".to_string(),
                        suspicious: !line.contains("backup") && !line.contains("cleanup"),
                        reason: "Potential suspicious cron job".to_string(),
                    });
                }
            }
        }
        info!("Found {} persistence entries on Unix", entries.len());
    }
    #[cfg(target_os = "windows")]
    {
        let cmd = crate::common::hidden_cmd("reg").args(&["query", "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"]).output();
        if let Ok(output) = cmd {
            let output_str = String::from_utf8_lossy(&output.stdout);
            for line in output_str.lines() {
                if line.contains("REG_SZ") {
                    entries.push(PersistenceEntry {
                        name: "Registry Run".to_string(),
                        path: "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run".to_string(),
                        command: line.to_string(),
                        enabled: true,
                        source: "Windows Registry".to_string(),
                        suspicious: false,
                        reason: "Startup entry".to_string(),
                    });
                }
            }
            info!("Found {} persistence entries in Windows Registry", entries.len());
        }
    }
    entries
}
// ============ Privilege Escalation Functions ============
/// Check privilege escalation vectors
pub fn check_privilege_escalation() -> Vec<PrivilegeEscalationResult> {
    debug!("Checking privilege escalation vectors");
    let mut results = Vec::new();
    #[cfg(not(target_os = "windows"))]
    {
        let checks = [
            ("SUID Binaries", "find / -perm -4000 -type f 2>/dev/null"),
            ("SGID Binaries", "find / -perm -2000 -type f 2>/dev/null"),
            ("Sudo rights", "sudo -l 2>/dev/null"),
            ("Writeable system files", "find /etc -writable 2>/dev/null"),
            ("Docker socket", "test -S /var/run/docker.sock"),
        ];
        for (name, cmd) in checks {
            let output = crate::common::hidden_cmd("sh").args(&["-c", cmd]).output();
            if let Ok(output) = output {
                let output_str = String::from_utf8_lossy(&output.stdout);
                let vulnerable = !output_str.is_empty() && !output_str.contains("not allowed");
                results.push(PrivilegeEscalationResult {
                    check_name: name.to_string(),
                    vulnerable,
                    description: format!("Checking for {}", name),
                    details: if output_str.is_empty() {
                        "No findings".to_string()
                    } else {
                        output_str.lines().take(5).collect::<Vec<_>>().join("\n")
                    },
                    severity: if vulnerable { "high" } else { "low" }.to_string(),
                });
            }
        }
        info!("Privilege escalation check complete: {} results", results.len());
    }
    #[cfg(target_os = "windows")]
    {
        let checks = [
            ("Admin Group", "net localgroup administrators"),
            ("UAC Status", "reg query HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"),
        ];
        for (name, cmd) in checks {
            let output = crate::common::hidden_cmd("cmd").args(&["/C", cmd]).output();
            if let Ok(output) = output {
                let output_str = String::from_utf8_lossy(&output.stdout);
                results.push(PrivilegeEscalationResult {
                    check_name: name.to_string(),
                    vulnerable: name == "Admin Group" && output_str.contains("Administrator"),
                    description: format!("Checking for {}", name),
                    details: output_str.lines().take(5).collect::<Vec<_>>().join("\n"),
                    severity: if name == "Admin Group" { "high" } else { "medium" }.to_string(),
                });
            }
        }
        info!("Privilege escalation check complete on Windows: {} results", results.len());
    }
    results
}
// ============ Patch Detection Functions ============
/// Check patch status
pub fn check_patch_status() -> PatchScanResult {
    debug!("Checking patch status");
    let mut patches = Vec::new();
    #[cfg(not(target_os = "windows"))]
    {
        let cmd = crate::common::hidden_cmd("sh")
            .args(&["-c", "apt list --upgradable 2>/dev/null || yum check-update 2>/dev/null || dnf check-update 2>/dev/null"])
            .output();
        if let Ok(output) = cmd {
            let output_str = String::from_utf8_lossy(&output.stdout);
            for line in output_str.lines() {
                if !line.is_empty() && !line.starts_with("Loading") && !line.starts_with("Available") {
                    let parts: Vec<&str> = line.split_whitespace().collect();
                    if let Some(name) = parts.first() {
                        let version = parts.get(1).unwrap_or(&"").to_string();
                        let severity = if name.contains("kernel") || name.contains("security") {
                            "critical"
                        } else if name.contains("openssl") || name.contains("ssh") {
                            "high"
                        } else {
                            "medium"
                        };
                        patches.push(PatchInfo {
                            name: name.to_string(),
                            installed: false,
                            version,
                            release_date: None,
                            severity: severity.to_string(),
                            description: "Security update available".to_string(),
                        });
                    }
                }
            }
            info!("Found {} missing patches on Linux", patches.len());
        }
    }
    #[cfg(target_os = "windows")]
    {
        let cmd = crate::common::hidden_cmd("powershell").args(&["-Command", "Get-WindowsUpdate -IsInstalled | Select-Object -First 20"]).output();
        if let Ok(output) = cmd {
            let output_str = String::from_utf8_lossy(&output.stdout);
            for line in output_str.lines() {
                if !line.is_empty() && !line.contains("KB") {
                    patches.push(PatchInfo {
                        name: line.to_string(),
                        installed: true,
                        version: "".to_string(),
                        release_date: None,
                        severity: "low".to_string(),
                        description: "Windows update installed".to_string(),
                    });
                }
            }
            info!("Found {} patches on Windows", patches.len());
        }
    }
    let total_checked = patches.len();
    let installed = patches.iter().filter(|p| p.installed).count();
    let missing = patches.iter().filter(|p| !p.installed).count();
    PatchScanResult { total_checked, installed, missing, patches }
}
// ============ Registry Monitor Functions (Windows) ============
/// Monitor Windows registry key
#[cfg(target_os = "windows")]
pub fn monitor_registry_key(path: &str) -> RegistryKeyInfo {
    debug!("Monitoring registry key: {}", path);
    let cmd = crate::common::hidden_cmd("reg").args(&["query", path]).output();
    let mut issues = Vec::new();
    let name = path.split('\\').last().unwrap_or(path);
    if let Ok(output) = cmd {
        let output_str = String::from_utf8_lossy(&output.stdout);
        let value = output_str.lines().next().unwrap_or("No data").to_string();
        if path.contains("Run") {
            issues.push("Startup registry key - potential persistence".to_string());
        }
        if path.contains("Services") {
            issues.push("Service registry key - requires admin privileges".to_string());
        }
        info!("Registry key monitored: {}", path);
        RegistryKeyInfo {
            path: path.to_string(),
            name: name.to_string(),
            value,
            value_type: "REG_SZ".to_string(),
            last_modified: "".to_string(),
            security_issues: issues,
        }
    } else {
        info!("Registry key not accessible: {}", path);
        RegistryKeyInfo {
            path: path.to_string(),
            name: name.to_string(),
            value: "Key not found".to_string(),
            value_type: "unknown".to_string(),
            last_modified: "".to_string(),
            security_issues: vec!["Registry key not accessible".to_string()],
        }
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_is_password_weak() {
        let (weak, reason) = is_password_weak("password");
        assert!(weak);
        assert!(!reason.is_empty());
        let (weak, _) = is_password_weak("MySecureP@ssw0rd123");
        assert!(!weak);
    }
    #[test]
    fn test_get_password_strength() {
        let strength = get_password_strength("123456");
        assert_eq!(strength, PasswordStrength::Weak);
        let strength = get_password_strength("MySecureP@ssw0rd123");
        assert_eq!(strength, PasswordStrength::Strong);
    }
    #[test]
    fn test_query_cve() {
        let cve = query_cve("CVE-2024-1234");
        assert!(cve.is_some());
        assert_eq!(cve.unwrap().id, "CVE-2024-1234");
        let cve = query_cve("CVE-9999-9999");
        assert!(cve.is_none());
    }
    #[test]
    fn test_query_cves_by_keyword() {
        let results = query_cves_by_keyword("sql");
        assert!(!results.is_empty());
        assert!(results.iter().any(|c| c.id.contains("5678")));
    }
    #[test]
    fn test_query_threat_intel() {
        let result = query_threat_intel("8.8.8.8");
        assert!(!result.malicious);
        let result = query_threat_intel("185.130.5.253");
        assert!(result.malicious);
        assert!(result.confidence > 0.0);
    }
    #[test]
    fn test_detect_phishing() {
        let result = detect_phishing("https://secure-login.example.com");
        assert!(result.is_phishing || !result.reasons.is_empty());
        let result = detect_phishing("https://google.com");
        assert!(!result.is_phishing);
    }
    #[test]
    fn test_check_security_policies() {
        let results = check_security_policies();
        assert!(!results.is_empty());
        assert!(results.iter().any(|r| r.policy_name == "password_min_length"));
    }
    #[test]
    fn test_check_file_permissions() {
        let result = check_file_permissions("/tmp");
        assert!(result.exists);
        // The test may fail on some systems, but it's a reasonable check
        assert!(result.readable);
    }
    #[test]
    fn test_generate_password_dict() {
        let dict = generate_password_dict("test", 10);
        assert!(!dict.is_empty());
        assert!(dict.len() <= 10);
        assert!(dict.iter().any(|p| p.contains("test")));
    }
}