winaudit 0.1.3

Advanced Windows auditing and security assessment Crate in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
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
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
//! This module provide OS Security checks for Windows systems

#![allow(non_camel_case_types)]
#![allow(unused_imports)]

use crate::{WinAuditError, hresult_to_audit_error, win32_to_audit_error};
use std::ffi::{OsStr, OsString};
use std::fmt;
use std::os::raw::c_void;
use std::os::windows::ffi::OsStrExt as _;

use std::process::Command;
use windows::Win32::Devices::Bluetooth::{
    BLUETOOTH_FIND_RADIO_PARAMS, BLUETOOTH_RADIO_INFO, BluetoothFindFirstRadio,
    BluetoothFindRadioClose, BluetoothGetRadioInfo,
};
use windows::Win32::Foundation::{
    CloseHandle, ERROR_SUCCESS, GetLastError, HANDLE, INVALID_HANDLE_VALUE, WIN32_ERROR,
};
use windows::Win32::NetworkManagement::NetManagement::*;
use windows::Win32::NetworkManagement::WiFi::*;
use windows::Win32::Storage::FileSystem::*;
use windows::Win32::System::Com::{
    CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, CoCreateInstance, CoInitializeEx,
    CoUninitialize,
};
use windows::Win32::System::Registry::{
    REG_ROUTINE_FLAGS, REG_SAM_FLAGS, REG_VALUE_TYPE, RRF_RT_REG_BINARY, RRF_RT_REG_DWORD,
    RRF_RT_REG_SZ, RegCloseKey, RegEnumValueW, RegGetValueW, RegOpenKeyExA, RegOpenKeyExW,
    RegQueryValueExA,
};
use windows::Win32::System::SystemInformation::*;
use windows::Win32::System::SystemServices::PROCESS_MITIGATION_ASLR_POLICY;
use windows::Win32::System::Threading::{
    GetCurrentProcess, GetProcessDEPPolicy, GetProcessMitigationPolicy,
    PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION, PROCESS_DEP_ENABLE, ProcessASLRPolicy,
};
use windows::Win32::System::UpdateAgent::{IUpdateSearcher, IUpdateSession};
use windows::core::{
    BSTR, Error as WinError, Interface, PCSTR, PCWSTR, PWSTR, Result as WinResult,
};
use windows_core::{BOOL, GUID, HRESULT};
use winreg::RegKey;
use winreg::enums::*;

// Import RtlGetVersion from ntdll.dll
#[link(name = "ntdll")]
unsafe extern "system" {
    unsafe fn RtlGetVersion(lpVersionInformation: *mut OSVERSIONINFOEXW) -> i32;
}

// Import DeviceIoControl from kernel32.dll
#[link(name = "kernel32")]
unsafe extern "system" {
    pub(crate) unsafe fn DeviceIoControl(
        hDevice: HANDLE,
        dwIoControlCode: u32,
        lpInBuffer: *const std::ffi::c_void,
        nInBufferSize: u32,
        lpOutBuffer: *mut std::ffi::c_void,
        nOutBufferSize: u32,
        lpBytesReturned: *mut u32,
        lpOverlapped: *mut std::ffi::c_void,
    ) -> i32;
}

/// This struct represent windows version
///
/// # Fields:
/// - *win_ver*: The windows version example 11, 10, 8.1
/// - *build_number*: The windows build number example 22000
pub struct WinVer {
    pub win_ver: f32,
    pub build_number: u16,
}

/// All Windows versions that reached End-of-Life (without build numbers)
pub const WINVERSION_END_OF_LIFE: &[f32] = &[
    3.1,    // Windows 3.1
    95.0,   // Windows 95
    98.0,   // Windows 98
    98.1,   // Windows 98 SE
    2000.0, // Windows 2000
    4.9,    // Windows ME
    5.1,    // Windows XP
    6.0,    // Windows Vista
    7.0,    // Windows 7
    8.0,    // Windows 8
    8.1,    // Windows 8.1
    10.0,   // Windows 10 (some builds)
];

/// Windows 11 build numbers
pub const WINBUILD_11_END_OF_LIFE: &[u16] = &[
    21, // 21H2
    22, // 22H2
    23, // 23H2
];

macro_rules! audit_try {
    ($audit:expr, $expr:expr) => {
        $expr.map_err(|e| WinAuditError::WinAuditError {
            failed_audit: $audit,
            source: e,
        })
    };
}

/// Get the current Windows version and build number
///
/// # Example Usage
/// ```
/// use winaudit::get_current_windows_version;
///
/// match get_current_windows_version() {
///     Ok(version) => {
///         println!("Current Windows version: {}", version.win_ver);
///         println!("Current Windows build number: {}", version.build_number);
///     }
///     Err(error) => {
///         eprintln!("Error: {}", error);
///     }
/// }
/// ```
pub fn get_current_windows_version() -> Result<WinVer, WinAuditError> {
    unsafe {
        let mut os_info: OSVERSIONINFOEXW = std::mem::zeroed();
        os_info.dwOSVersionInfoSize = std::mem::size_of::<OSVERSIONINFOEXW>() as u32;

        let status = RtlGetVersion(&mut os_info as *mut _);

        if status == 0 {
            Ok(WinVer {
                win_ver: os_info.dwMajorVersion as f32 + os_info.dwMinorVersion as f32 / 10.0,
                build_number: os_info.dwBuildNumber as u16,
            })
        } else {
            Err(WinAuditError::WinAuditError {
                failed_audit: "Failed to get Windows version",
                source: WinError::from_hresult(windows_core::HRESULT(status)),
            })
        }
    }
}

/// Check is the Windows Version currently running is EOL, This important for Security
///
/// # Example Usage:
/// ```
/// use winaudit::is_win_version_eol;
///
/// match is_win_version_eol() {
///     Ok(is_eol) => {
///         if is_eol {
///             println!("The current Windows version is End-of-Life.");
///         } else {
///             println!("The current Windows version is not End-of-Life.");
///         }
///     }
///   Err(error) => {
///         eprintln!("Error: {}", error);
///     }
/// }
/// ```
pub fn is_win_version_eol() -> Result<bool, WinAuditError> {
    let current = get_current_windows_version()?;

    if WINVERSION_END_OF_LIFE.contains(&current.win_ver) {
        Ok(true)
    } else {
        // Check the Build of Windows 11 is not EOL
        Ok(WINBUILD_11_END_OF_LIFE.contains(&current.build_number))
    }
}

/// This check is the windows version safe and supported not EOL
/// This counterpart of `is_win_version_eol`
///
/// # Example Usage:
/// ```
/// use winaudit::is_win_version_safe;
///
/// match is_win_version_safe() {
///     Ok(is_safe) => {
///         if is_safe {
///             println!("The current Windows version is safe and supported.");
///         } else {
///             println!("The current Windows version is not safe or not supported.");
///         }
///     }
///    Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
///
pub fn is_win_version_safe() -> Result<bool, WinAuditError> {
    Ok(!is_win_version_eol()?)
}

/// Check is ASLR (Address Space Layout Randomization) enabled for the current process.
///
/// # Example Usage:
/// ```
/// use winaudit::is_aslr_enabled_for_current_process;
///
/// match is_aslr_enabled_for_current_process() {
///     Ok(is_enabled) => {
///         if is_enabled {
///             println!("ASLR is enabled for the current process.");
///         } else {
///             println!("ASLR is not enabled for the current process.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
///
pub fn is_aslr_enabled_for_current_process() -> Result<bool, WinAuditError> {
    unsafe {
        let mut policy = PROCESS_MITIGATION_ASLR_POLICY::default();

        let result: Result<(), windows_core::Error> = GetProcessMitigationPolicy(
            GetCurrentProcess(),
            ProcessASLRPolicy,
            &mut policy as *mut _ as *mut _,
            std::mem::size_of::<PROCESS_MITIGATION_ASLR_POLICY>(),
        );

        match result {
            Ok(()) => {
                let flags = policy.Anonymous.Flags;
                let enable_bottom_up_randomization = (flags & 0x1) != 0;
                let enable_force_relocate_images = (flags & 0x2) != 0;
                let enable_high_entropy = (flags & 0x4) != 0;

                Ok(enable_bottom_up_randomization
                    || enable_force_relocate_images
                    || enable_high_entropy)
            }
            Err(err) => Err(WinAuditError::WinAuditError {
                failed_audit: "Failed to query ASLR policy for current process",
                source: err,
            }),
        }
    }
}

/// Check is the ASLR (Address Space Layout Randomization) enabled at system level.
///
/// # Example Usage:
/// ```
/// use winaudit::is_aslr_enabled_for_system;
///
/// match is_aslr_enabled_for_system() {
///     Ok(is_enabled) => {
///         if is_enabled {
///             println!("ASLR is enabled at system level.");
///         } else {
///             println!("ASLR is not enabled at system level.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
pub fn is_aslr_enabled_for_system() -> Result<bool, WinAuditError> {
    unsafe {
        let mut value: u32 = 0;
        let mut size = std::mem::size_of::<u32>() as u32;

        let subkey: Vec<u16> =
            OsStr::new("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Memory Management")
                .encode_wide()
                .chain(std::iter::once(0))
                .collect();

        let valuename: Vec<u16> = OsStr::new("MoveImages")
            .encode_wide()
            .chain(std::iter::once(0))
            .collect();

        let win_result = RegGetValueW(
            windows::Win32::System::Registry::HKEY(HKEY_LOCAL_MACHINE),
            PCWSTR(subkey.as_ptr()),
            PCWSTR(valuename.as_ptr()),
            RRF_RT_REG_DWORD,
            None,
            Some(&mut value as *mut _ as *mut c_void),
            Some(&mut size),
        );

        if win_result != WIN32_ERROR(0) {
            return Err(WinAuditError::WinAuditError {
                failed_audit: "Failed to read MoveImages registry value",
                source: WinError::from(win_result),
            });
        }

        if value != 0 {
            return Ok(true);
        }

        let kernel_subkey: Vec<u16> =
            OsStr::new("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Kernel")
                .encode_wide()
                .chain(std::iter::once(0))
                .collect();

        let kernel_value: Vec<u16> = OsStr::new("MitigationOptions")
            .encode_wide()
            .chain(std::iter::once(0))
            .collect();

        let mut mitigation_data = [0u8; 8];
        let mut mitigation_size = mitigation_data.len() as u32;

        let kernel_win_result = RegGetValueW(
            windows::Win32::System::Registry::HKEY(HKEY_LOCAL_MACHINE),
            PCWSTR(kernel_subkey.as_ptr()),
            PCWSTR(kernel_value.as_ptr()),
            RRF_RT_REG_BINARY,
            None,
            Some(mitigation_data.as_mut_ptr() as *mut _),
            Some(&mut mitigation_size),
        );

        if kernel_win_result != WIN32_ERROR(0) {
            return Err(WinAuditError::WinAuditError {
                failed_audit: "Failed to read MitigationOptions registry value",
                source: WinError::from(kernel_win_result),
            });
        }

        let mitigation_flags = u64::from_le_bytes(mitigation_data);
        Ok((mitigation_flags & 0x3) != 0)
    }
}

/// Check is only Administrator users exist in the system
/// If only Administrator this is a security risk
///
/// Users encourged to create an normal user
///
/// # Example Usage:
///
/// ```
/// use winaudit::is_only_administrator_user_exist;
///
/// match is_only_administrator_user_exist() {
///     Ok(is_only_admin) => {
///         if is_only_admin {
///             println!("Only administrator user exists in the system.");
///         } else {
///             println!("More than one user exists in the system.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
///
/// ```
pub fn is_only_administrator_user_exist() -> Result<bool, WinAuditError> {
    unsafe {
        let mut buffer: *mut USER_INFO_0 = std::ptr::null_mut();
        let mut entries_read: u32 = 0;
        let mut total_entries: u32 = 0;

        let status = NetUserEnum(
            PCWSTR::null(),
            0,
            FILTER_NORMAL_ACCOUNT,
            &mut buffer as *mut _ as *mut _,
            MAX_PREFERRED_LENGTH,
            &mut entries_read,
            &mut total_entries,
            None,
        );

        if status != NERR_Success {
            return Err(WinAuditError::WinAuditError {
                failed_audit: "NetUserEnum failed",
                source: WinError::from(WIN32_ERROR(status as u32)),
            });
        }

        let users = std::slice::from_raw_parts(buffer, entries_read as usize);
        let mut user_count = 0;
        let mut has_non_admin = false;

        for user in users {
            if !user.usri0_name.is_null() {
                let wide = windows::core::PCWSTR(user.usri0_name.0);
                let len = (0..).take_while(|&i| *wide.0.add(i) != 0).count();
                let username = String::from_utf16_lossy(std::slice::from_raw_parts(wide.0, len));

                user_count += 1;

                if username.to_lowercase() != "administrator" {
                    has_non_admin = true;
                    break;
                }
            }
        }

        NetApiBufferFree(Some(buffer as *mut _));

        Ok(user_count == 1 && !has_non_admin)
    }
}

/// This check is Windows Security Questions disabled
/// This important to security!
///
/// Security Questions are unsafe for reset password, Because theses answers may already exist on Social Media or The Internet
///
/// # Example Usage:
/// ```
/// use winaudit::is_security_questions_disabled;
///
/// match is_security_questions_disabled() {
///     Ok(is_disabled) => {
///         if is_disabled {
///             println!("Security questions are disabled.");
///         } else {
///             println!("Security questions are not disabled.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
pub fn is_security_questions_disabled() -> Result<bool, WinAuditError> {
    unsafe {
        const CHECKS: &[(&str, &str)] = &[
            (
                "SOFTWARE\\Policies\\Microsoft\\Windows\\System",
                "TurnOffSecurityQuestions",
            ),
            (
                "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System",
                "SecurityQuestionsDisabled",
            ),
            (
                "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System",
                "NoLocalPasswordReset",
            ),
            (
                "SOFTWARE\\Policies\\Microsoft\\Windows\\System\\PasswordReset",
                "Disable",
            ),
        ];

        let mut hkey: windows::Win32::System::Registry::HKEY =
            windows::Win32::System::Registry::HKEY::default();

        for (subkey, value_name) in CHECKS {
            let path: Vec<u16> = subkey.encode_utf16().chain(Some(0)).collect();

            if RegOpenKeyExW(
                windows::Win32::System::Registry::HKEY(HKEY_LOCAL_MACHINE),
                PCWSTR(path.as_ptr()),
                Some(0),
                REG_SAM_FLAGS(KEY_READ),
                &mut hkey,
            ) != WIN32_ERROR(0)
            {
                continue;
            }

            let name: Vec<u16> = value_name.encode_utf16().chain(Some(0)).collect();
            let mut data: u32 = 0;
            let mut size = std::mem::size_of::<u32>() as u32;

            let reg_res = RegGetValueW(
                hkey,
                PCWSTR(std::ptr::null()),
                PCWSTR(name.as_ptr()),
                RRF_RT_REG_DWORD,
                None,
                Some(&mut data as *mut _ as *mut _),
                Some(&mut size),
            );

            if reg_res == WIN32_ERROR(0) {
                if data == 1 {
                    return Ok(true);
                }
            } else {
                let mut buffer: [u16; 512] = [0; 512];
                let mut buf_size = buffer.len() as u32 * 2;

                let string_res = RegGetValueW(
                    hkey,
                    PCWSTR(std::ptr::null()),
                    PCWSTR(name.as_ptr()),
                    RRF_RT_REG_SZ,
                    None,
                    Some(buffer.as_mut_ptr() as *mut _),
                    Some(&mut buf_size),
                );

                if string_res == WIN32_ERROR(0) {
                    let s = String::from_utf16_lossy(&buffer[..(buf_size / 2) as usize]);
                    let sval = s.trim().to_lowercase();
                    if sval == "1" || sval == "true" || sval == "yes" {
                        return Ok(true);
                    }
                }
            }
        }

        Ok(false)
    }
}

/// Check is bitlocker enabled or not.
///
/// BitLocker is a software for Encrypting drives.
///
/// # Example Usage:
/// ```
/// use winaudit::is_bitlocker_enabled;
///
/// match is_bitlocker_enabled() {
///     Ok(is_enabled) => {
///         if is_enabled {
///             println!("BitLocker is enabled.");
///         } else {
///             println!("BitLocker is not enabled.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
///

pub fn is_bitlocker_enabled() -> Result<bool, WinAuditError> {
    use windows::Win32::System::Registry::HKEY;
    unsafe {
        const BITLOCKER_REG_KEY: &str = r"SOFTWARE\Policies\Microsoft\FVE";
        const BITLOCKER_ENABLED_VALUES: &[&str] = &[
            "RDVPassphraseEnabled",
            "UseBitLockerToGo",
            "EnableBDEWithNoTPM",
            "FDVRequireActiveDirectoryBackup",
        ];

        let hklm = HKEY_LOCAL_MACHINE;

        let mut key = windows::Win32::System::Registry::HKEY::default();
        let path: Vec<u16> = BITLOCKER_REG_KEY.encode_utf16().chain(Some(0)).collect();

        if RegOpenKeyExW(
            HKEY(hklm),
            PCWSTR(path.as_ptr()),
            Some(0),
            REG_SAM_FLAGS(KEY_READ),
            &mut key,
        ) == WIN32_ERROR(0)
        {
            for name in BITLOCKER_ENABLED_VALUES {
                let name_w: Vec<u16> = name.encode_utf16().chain(Some(0)).collect();
                let mut data: u32 = 0;
                let mut size = std::mem::size_of::<u32>() as u32;

                let res = RegGetValueW(
                    key,
                    PCWSTR(std::ptr::null()),
                    PCWSTR(name_w.as_ptr()),
                    RRF_RT_REG_DWORD,
                    None,
                    Some(&mut data as *mut _ as *mut _),
                    Some(&mut size),
                );

                if res == WIN32_ERROR(0) && data == 1 {
                    return Ok(true);
                }
            }
        }

        let output: Result<std::process::Output, std::io::Error> = std::process::Command::new("sc")
            .args(&["query", "BDESVC"])
            .output();

        if let Ok(output) = output {
            if String::from_utf8_lossy(&output.stdout).contains("RUNNING") {
                return Ok(true);
            }
        }

        Ok(false)
    }
}

/// Check is a specific drive locked by BitLocker
///
/// # Example Usage:
/// ```
/// use winaudit::is_drive_locked_with_bitlocker;
///
/// match is_drive_locked_with_bitlocker("C:") {
///     Ok(is_locked) => {
///         if is_locked {
///             println!("The drive is locked by BitLocker.");
///         } else {
///             println!("The drive is not locked by BitLocker.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
///
pub fn is_drive_locked_with_bitlocker(drive_letter: &str) -> Result<bool, WinAuditError> {
    if !is_bitlocker_enabled()? {
        return Ok(false);
    }

    let mut path = drive_letter.trim().to_string();
    if !path.ends_with('\\') {
        path.push('\\');
    }

    let wide: Vec<u16> = OsStr::new(&path).encode_wide().chain(Some(0)).collect();
    let mut volume_name = [0u16; 256];
    let mut fs_name = [0u16; 256];
    let mut serial_number = 0u32;
    let mut max_comp_len = 0u32;
    let mut fs_flags = 0u32;

    let res = unsafe {
        GetVolumeInformationW(
            PCWSTR(wide.as_ptr()),
            Some(&mut volume_name),
            Some(&mut serial_number),
            Some(&mut max_comp_len),
            Some(&mut fs_flags),
            Some(&mut fs_name),
        )
    };

    if res.is_err() {
        return Ok(false);
    }

    if let Ok(output) = Command::new("manage-bde")
        .args(&["-status", drive_letter])
        .output()
    {
        let stdout = String::from_utf8_lossy(&output.stdout);
        if stdout.contains("Protection On")
            || stdout.contains("Percentage Encrypted")
            || stdout.contains("Fully Encrypted")
        {
            return Ok(true);
        }
    }

    Ok(false)
}

/// Check if the system drive is locked with BitLocker
///
/// This the same like `is_drive_locked_with_bitlocker("C:")`
/// this designed for if windows not installed in `C:` drive.
///
/// # Example Usage:
/// ```
/// use winaudit::is_system_drive_locked_with_bitlocker;
///
/// match is_system_drive_locked_with_bitlocker() {
///     Ok(is_locked) => {
///         if is_locked {
///             println!("The system drive is locked by BitLocker.");
///         } else {
///             println!("The system drive is not locked by BitLocker.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
///

pub fn is_system_drive_locked_with_bitlocker() -> Result<bool, WinAuditError> {
    unsafe {
        let mut buffer = [0u16; 260];
        let len = GetWindowsDirectoryW(Some(&mut buffer[..])) as usize;

        let drive_letter = if len == 0 || len >= buffer.len() {
            "C:".to_string()
        } else {
            format!("{}:", char::from_u32(buffer[0] as u32).unwrap_or('C'))
        };

        is_drive_locked_with_bitlocker(&drive_letter)
    }
}

/// This check is SMBv1 enabled
///
/// This critical for security! Because has dangerous exploit `EternalBlue`
///
/// # Example Usage:
/// ```
/// use winaudit::is_smbv1_enabled;
///
/// match is_smbv1_enabled() {
///     Ok(is_enabled) => {
///         if is_enabled {
///             println!("SMBv1 is enabled.");
///         } else {
///             println!("SMBv1 is not enabled.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
pub fn is_smbv1_enabled() -> Result<bool, WinAuditError> {
    use windows::Win32::System::Registry::HKEY;
    unsafe {
        let hklm = HKEY_LOCAL_MACHINE;

        const CHECKS: &[(&str, &str)] = &[
            (
                "SYSTEM\\CurrentControlSet\\Services\\LanmanServer\\Parameters",
                "SMB1",
            ),
            ("SYSTEM\\CurrentControlSet\\Services\\mrxsmb10", "Start"),
        ];

        for (subkey_str, value_name_str) in CHECKS {
            let subkey: Vec<u16> = subkey_str.encode_utf16().chain(Some(0)).collect();
            let mut key = windows::Win32::System::Registry::HKEY::default();
            let open_res = RegOpenKeyExW(
                HKEY(hklm),
                PCWSTR(subkey.as_ptr()),
                Some(0),
                REG_SAM_FLAGS(KEY_READ),
                &mut key,
            );
            if open_res != WIN32_ERROR(0) {
                continue;
            }

            let value_name: Vec<u16> = value_name_str.encode_utf16().chain(Some(0)).collect();
            let mut data: u32 = 0;
            let mut size: u32 = std::mem::size_of::<u32>() as u32;

            let get_res = RegGetValueW(
                key,
                PCWSTR(std::ptr::null()),
                PCWSTR(value_name.as_ptr()),
                RRF_RT_REG_DWORD,
                None,
                Some(&mut data as *mut _ as *mut _),
                Some(&mut size),
            );

            if get_res == WIN32_ERROR(0) && data != 0 {
                return Ok(true);
            }
        }

        Ok(false)
    }
}

/// Latest SMB version constant
pub const LATEST_SMB_VERSION: f32 = 3.1;

/// Check is the current SMB version is the latest
///
/// # Example Usage:
/// ```
/// use winaudit::is_smb_version_latest;
///
/// match is_smb_version_latest() {
///     Ok(is_latest) => {
///         if is_latest {
///             println!("The current SMB version is the latest.");
///         } else {
///             println!("The current SMB version is not the latest.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```

pub fn is_smb_version_latest() -> Result<bool, WinAuditError> {
    use windows::Win32::System::Registry::HKEY;
    unsafe {
        let hklm = HKEY_LOCAL_MACHINE;

        let server_path: Vec<u16> = "SYSTEM\\CurrentControlSet\\Services\\LanmanServer\\Parameters"
            .encode_utf16()
            .chain(Some(0))
            .collect();
        let mut server_key = windows::Win32::System::Registry::HKEY::default();
        let open_server_res = RegOpenKeyExW(
            HKEY(hklm),
            PCWSTR(server_path.as_ptr()),
            Some(0),
            REG_SAM_FLAGS(KEY_READ),
            &mut server_key,
        );
        win32_to_audit_error(open_server_res, "RegOpenKeyExW (LanmanServer Parameters)")?;

        let value_name: Vec<u16> = "SMB2".encode_utf16().chain(Some(0)).collect();
        let mut smb2: u32 = 0;
        let mut size: u32 = std::mem::size_of::<u32>() as u32;
        let get_smb2_res = RegGetValueW(
            server_key,
            PCWSTR(std::ptr::null()),
            PCWSTR(value_name.as_ptr()),
            RRF_RT_REG_DWORD,
            None,
            Some(&mut smb2 as *mut _ as *mut _),
            Some(&mut size),
        );

        if get_smb2_res == WIN32_ERROR(0) && smb2 != 0 {
            return Ok(true);
        }

        let client_path: Vec<u16> = "SYSTEM\\CurrentControlSet\\Services\\mrxsmb20"
            .encode_utf16()
            .chain(Some(0))
            .collect();
        let mut client_key = windows::Win32::System::Registry::HKEY::default();
        let open_client_res = RegOpenKeyExW(
            HKEY(hklm),
            PCWSTR(client_path.as_ptr()),
            Some(0),
            REG_SAM_FLAGS(KEY_READ),
            &mut client_key,
        );
        win32_to_audit_error(open_client_res, "RegOpenKeyExW (mrxsmb20)")?;

        let value_name_start: Vec<u16> = "Start".encode_utf16().chain(Some(0)).collect();
        let mut start: u32 = 0;
        let mut start_size: u32 = std::mem::size_of::<u32>() as u32;
        let get_start_res = RegGetValueW(
            client_key,
            PCWSTR(std::ptr::null()),
            PCWSTR(value_name_start.as_ptr()),
            RRF_RT_REG_DWORD,
            None,
            Some(&mut start as *mut _ as *mut _),
            Some(&mut start_size),
        );

        if get_start_res == WIN32_ERROR(0) && start != 0 {
            return Ok(true);
        }

        Ok(false)
    }
}

/// Check is the SMB server allows anonymous login, No username or password
///
/// # Example Usage:
/// ```
/// use winaudit::is_smb_server_allow_anonymous_login;
///
/// match is_smb_server_allow_anonymous_login() {
///     Ok(is_allowed) => {
///         if is_allowed {
///             println!("The SMB server allows anonymous login.");
///         } else {
///             println!("The SMB server does not allow anonymous login.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
pub fn is_smb_server_allow_anonymous_login() -> Result<bool, WinAuditError> {
    unsafe {
        let hklm = HKEY_LOCAL_MACHINE;

        let restrict_path: Vec<u16> = "SYSTEM\\CurrentControlSet\\Control\\Lsa"
            .encode_utf16()
            .chain(Some(0))
            .collect();
        let mut hkey = windows::Win32::System::Registry::HKEY::default();
        let open_res = RegOpenKeyExW(
            windows::Win32::System::Registry::HKEY(hklm),
            PCWSTR(restrict_path.as_ptr()),
            Some(0),
            REG_SAM_FLAGS(KEY_READ),
            &mut hkey,
        );
        win32_to_audit_error(open_res, "RegOpenKeyExW (RestrictAnonymous)")?;

        let value_name: Vec<u16> = "RestrictAnonymous".encode_utf16().chain(Some(0)).collect();
        let mut data: u32 = 0;
        let mut size: u32 = std::mem::size_of::<u32>() as u32;
        let get_res = RegGetValueW(
            hkey,
            PCWSTR(std::ptr::null()),
            PCWSTR(value_name.as_ptr()),
            RRF_RT_REG_DWORD,
            None,
            Some(&mut data as *mut _ as *mut _),
            Some(&mut size),
        );
        win32_to_audit_error(get_res, "RegGetValueW (RestrictAnonymous)")?;

        if data == 0 {
            return Ok(true);
        }

        let shares_path: Vec<u16> = "SYSTEM\\CurrentControlSet\\Services\\LanmanServer\\Shares"
            .encode_utf16()
            .chain(Some(0))
            .collect();
        let mut shares_key = windows::Win32::System::Registry::HKEY::default();
        let open_shares_res = RegOpenKeyExW(
            windows::Win32::System::Registry::HKEY(hklm),
            PCWSTR(shares_path.as_ptr()),
            Some(0),
            REG_SAM_FLAGS(KEY_READ),
            &mut shares_key,
        );
        if open_shares_res == WIN32_ERROR(0) {
            let mut index: u32 = 0;
            loop {
                let mut name_buffer = [0u16; 256];
                let mut name_size = name_buffer.len() as u32;
                let enum_res = RegEnumValueW(
                    shares_key,
                    index,
                    Some(PWSTR(name_buffer.as_mut_ptr())),
                    &mut name_size,
                    None,
                    None,
                    None,
                    None,
                );

                if enum_res != WIN32_ERROR(0) {
                    break;
                }

                let share_name = String::from_utf16_lossy(&name_buffer[..name_size as usize]);
                if !share_name.is_empty() {
                    return Ok(true);
                }

                index += 1;
            }
        }

        Ok(false)
    }
}

/// Check is Autorun/Autoplay enabled,
///
/// This important to Security!
///  malicious USBS can deploy malwares automatically and silently without noticing.
///
/// # Example Usage
/// ```
/// use winaudit::is_autorun_enabled;
///
/// match is_autorun_enabled() {
///     Ok(is_enabled) => {
///         if is_enabled {
///             println!("Autorun/Autoplay is enabled.");
///         } else {
///             println!("Autorun/Autoplay is not enabled.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
pub fn is_autorun_enabled() -> Result<bool, WinAuditError> {
    unsafe {
        let hives = [HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER];

        let keys = &[
            (
                "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer",
                "NoDriveTypeAutoRun",
            ),
            (
                "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer",
                "NoDriveAutoRun",
            ),
        ];

        for &hive in &hives {
            for (subkey_str, value_name_str) in keys {
                let mut hkey = windows::Win32::System::Registry::HKEY::default();

                let subkey: Vec<u16> = subkey_str.encode_utf16().chain(Some(0)).collect();
                let open_res = RegOpenKeyExW(
                    windows::Win32::System::Registry::HKEY(hive),
                    PCWSTR(subkey.as_ptr()),
                    Some(0),
                    REG_SAM_FLAGS(KEY_READ),
                    &mut hkey,
                );

                if open_res != WIN32_ERROR(0) {
                    continue;
                }

                let value_name: Vec<u16> = value_name_str.encode_utf16().chain(Some(0)).collect();
                let mut data: u32 = 0;
                let mut size: u32 = std::mem::size_of::<u32>() as u32;

                let get_res = RegGetValueW(
                    hkey,
                    PCWSTR(std::ptr::null()),
                    PCWSTR(value_name.as_ptr()),
                    RRF_RT_REG_DWORD,
                    None,
                    Some(&mut data as *mut _ as *mut _),
                    Some(&mut size),
                );

                if get_res != WIN32_ERROR(0) {
                    continue;
                }

                if data == 0 {
                    return Ok(true);
                }
            }
        }

        Ok(false)
    }
}

const FSCTL_GET_QUOTA_INFORMATION: u32 = 0x00090200;

#[repr(C)]
#[derive(Default)]
struct DISK_QUOTA_INFORMATION {
    used_space: u64,
    quota_limit: u64,
    threshold: u64,
    sid_length: u32,
    sid_offset: u32,
}

/// This check is quota enabled for specific Driver in current use scope.
///
/// enabling Quota are critical for security,
/// prevent malicious users to exhaust disks.
///
/// # Example Usage:
/// ```
/// use winaudit::is_quota_enabled_for;
///
/// match is_quota_enabled_for("C:") {
///     Ok(is_enabled) => {
///         if is_enabled {
///             println!("Quota is enabled for C: drive.");
///         } else {
///             println!("Quota is not enabled for C: drive.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
pub fn is_quota_enabled_for(drive_letter: &str) -> Result<bool, WinAuditError> {
    unsafe {
        let path_str = format!(r"\\.\{}", drive_letter.trim_end_matches(['\\', ':']));
        let path: Vec<u16> = OsStr::new(&path_str)
            .encode_wide()
            .chain(std::iter::once(0))
            .collect();

        let handle = match CreateFileW(
            PCWSTR(path.as_ptr()),
            FILE_READ_ATTRIBUTES.0 as u32,
            FILE_SHARE_READ | FILE_SHARE_WRITE,
            None,
            OPEN_EXISTING,
            FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS,
            None,
        ) {
            Ok(h) => h,
            Err(err) => {
                return Err(WinAuditError::WinAuditError {
                    failed_audit: "CreateFileW failed for drive",
                    source: err.into(),
                });
            }
        };

        if handle == INVALID_HANDLE_VALUE {
            return Err(WinAuditError::WinAuditError {
                failed_audit: "CreateFileW returned INVALID_HANDLE_VALUE",
                source: windows_core::Error::new(
                    windows_core::HRESULT(0),
                    "Invalid handle returned",
                ),
            });
        }

        let mut quota_info = DISK_QUOTA_INFORMATION::default();
        let mut bytes_returned = 0u32;

        let success = DeviceIoControl(
            handle,
            FSCTL_GET_QUOTA_INFORMATION,
            std::ptr::null(),
            0,
            &mut quota_info as *mut _ as *mut _,
            std::mem::size_of::<DISK_QUOTA_INFORMATION>() as u32,
            &mut bytes_returned,
            std::ptr::null_mut(),
        );

        let _ = CloseHandle(handle);

        if success == 0 {
            return Err(WinAuditError::WinAuditError {
                failed_audit: "DeviceIoControl(FSCTL_GET_QUOTA_INFORMATION) failed",
                source: windows_core::Error::new(
                    windows_core::HRESULT(0),
                    "Failed to query quota info",
                ),
            });
        }

        Ok(bytes_returned > 0)
    }
}

/// Check if the system has an account lockout policy enabled.
/// This important! for prevent brute force attacks against the target accounts in the system.
///
/// # Example Usage:
/// ```
/// use winaudit::is_account_lockout_policy_enabled;
///
/// match is_account_lockout_policy_enabled() {
///     Ok(is_enabled) => {
///         if is_enabled {
///             println!("Account lockout policy is enabled.");
///         } else {
///             println!("Account lockout policy is not enabled.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
pub fn is_account_lockout_policy_enabled() -> Result<bool, WinAuditError> {
    unsafe {
        let mut buffer: *mut core::ffi::c_void = std::ptr::null_mut();

        let status = NetUserModalsGet(PCWSTR::null(), 3, &mut buffer as *mut *mut _ as *mut *mut _);

        if status != NERR_Success {
            return Err(WinAuditError::WinAuditError {
                failed_audit: "NetUserModalsGet (Account Lockout Policy)",
                source: WIN32_ERROR(status as u32).into(),
            });
        }

        if buffer.is_null() {
            return Err(WinAuditError::WinAuditError {
                failed_audit: "NetUserModalsGet returned NULL buffer",
                source: windows_core::Error::new(
                    windows_core::HRESULT(0),
                    "NetUserModalsGet returned NULL buffer",
                ),
            });
        }

        let info = &*(buffer as *const USER_MODALS_INFO_3);
        let threshold = info.usrmod3_lockout_threshold;

        let _ = NetApiBufferFree(Some(buffer as *mut _));

        Ok(threshold > 0)
    }
}

const CLSID_UPDATE_SESSION: GUID = GUID::from_u128(0x4cb43d7f_7eee_4906_8698_60da1c38f2fe);

/// Check is update available in Windows Update
/// This important!, Updates includes bugs and vulnerability fixes and patches.
///
/// # Example Usage:
/// ```no_run
/// use winaudit::is_update_available;
///
/// match is_update_available() {
///     Ok(is_available) => {
///         if is_available {
///             println!("Update is available.");
///         } else {
///             println!("Update is not available.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
pub fn is_update_available() -> Result<bool, WinAuditError> {
    unsafe {
        hresult_to_audit_error(
            CoInitializeEx(Some(std::ptr::null_mut()), COINIT_APARTMENTTHREADED),
            "CoInitializeEx",
        )?;

        #[allow(unused_assignments)]
        let mut updates_available = false;

        let session: WinResult<IUpdateSession> =
            CoCreateInstance(&CLSID_UPDATE_SESSION, None, CLSCTX_INPROC_SERVER);

        let session = session.map_err(|e| WinAuditError::WinAuditError {
            failed_audit: "Create UpdateSession",
            source: e.into(),
        })?;

        let searcher =
            session
                .CreateUpdateSearcher()
                .map_err(|e| WinAuditError::WinAuditError {
                    failed_audit: "Create UpdateSearcher",
                    source: e.into(),
                })?;

        let criteria = BSTR::from("IsInstalled=0 and Type='Software' and IsHidden=0");

        let search_result =
            searcher
                .Search(&criteria)
                .map_err(|e| WinAuditError::WinAuditError {
                    failed_audit: "Search Windows Update",
                    source: e.into(),
                })?;

        let count = search_result
            .Updates()
            .and_then(|u| u.Count())
            .map_err(|e| WinAuditError::WinAuditError {
                failed_audit: "Get Update count",
                source: e.into(),
            })?;

        updates_available = count > 0;

        CoUninitialize();

        Ok(updates_available)
    }
}

/// Check is bluetooth enabled
/// This improve security because Bluetooth vulnerable to huge of attacks like `BlueJacking` and other...
///
/// # Example Usage
/// ```
/// use winaudit::is_bluetooth_enabled;
///
/// match is_bluetooth_enabled() {
///     Ok(is_enabled) => {
///         if is_enabled {
///             println!("Bluetooth is enabled.");
///         } else {
///             println!("Bluetooth is not enabled.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
pub fn is_bluetooth_enabled() -> Result<bool, WinAuditError> {
    unsafe {
        let mut params = BLUETOOTH_FIND_RADIO_PARAMS {
            dwSize: std::mem::size_of::<BLUETOOTH_FIND_RADIO_PARAMS>() as u32,
        };

        let mut radio_handle: HANDLE = HANDLE(std::ptr::null_mut());

        let find_handle = BluetoothFindFirstRadio(&mut params, &mut radio_handle).map_err(|e| {
            WinAuditError::WinAuditError {
                failed_audit: "Bluetooth FindFirstRadio",
                source: e.into(),
            }
        })?;

        if find_handle.is_invalid() || radio_handle.is_invalid() {
            return Ok(false);
        }

        let mut radio_info: BLUETOOTH_RADIO_INFO = std::mem::zeroed();
        radio_info.dwSize = std::mem::size_of::<BLUETOOTH_RADIO_INFO>() as u32;

        let win_result = BluetoothGetRadioInfo(radio_handle, &mut radio_info);

        if win_result != 0 {
            return Err(WinAuditError::WinAuditError {
                failed_audit: "Bluetooth GetRadioInfo",
                source: WIN32_ERROR(win_result).into(),
            });
        }

        let enabled = !radio_info.szName.is_empty();

        let _ = CloseHandle(radio_handle);
        let _ = BluetoothFindRadioClose(find_handle);

        Ok(enabled)
    }
}

/// Check is password policy is enforced
///
/// This important for security! Because some accounts in the system have weak passwords.
///
/// # Example Usage:
/// ```
/// use winaudit::is_strong_password_policy_enforced;
///
/// match is_strong_password_policy_enforced() {
///     Ok(is_enforced) => {
///         if is_enforced {
///             println!("Password policy is enforced.");
///         } else {
///             println!("Password policy is not enforced.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
pub fn is_strong_password_policy_enforced() -> Result<bool, WinAuditError> {
    use windows::Win32::System::Registry::HKEY;
    unsafe {
        let mut min_length: u32 = 0;
        let mut min_length_size = std::mem::size_of::<u32>() as u32;

        let path_min_length: Vec<u16> = "SYSTEM\\CurrentControlSet\\Services\\Netlogon\\Parameters"
            .encode_utf16()
            .chain(Some(0))
            .collect();
        let name_min_length: Vec<u16> = "MinimumPasswordLength"
            .encode_utf16()
            .chain(Some(0))
            .collect();

        let len_win_result = RegGetValueW(
            HKEY(HKEY_LOCAL_MACHINE),
            PCWSTR(path_min_length.as_ptr()),
            PCWSTR(name_min_length.as_ptr()),
            RRF_RT_REG_DWORD,
            None,
            Some(&mut min_length as *mut _ as *mut _),
            Some(&mut min_length_size),
        );
        win32_to_audit_error(len_win_result, "RegGetValueW (MinimumPasswordLength)")?;

        let mut complexity: u32 = 0;
        let mut complexity_size = std::mem::size_of::<u32>() as u32;

        let path_complexity: Vec<u16> = "SYSTEM\\CurrentControlSet\\Control\\Lsa"
            .encode_utf16()
            .chain(Some(0))
            .collect();
        let name_complexity: Vec<u16> =
            "PasswordComplexity".encode_utf16().chain(Some(0)).collect();

        let comp_win_result = RegGetValueW(
            HKEY(HKEY_LOCAL_MACHINE),
            PCWSTR(path_complexity.as_ptr()),
            PCWSTR(name_complexity.as_ptr()),
            RRF_RT_REG_DWORD,
            None,
            Some(&mut complexity as *mut _ as *mut _),
            Some(&mut complexity_size),
        );
        win32_to_audit_error(comp_win_result, "RegGetValueW (PasswordComplexity)")?;

        Ok(complexity == 1 && min_length >= 12)
    }
}

/// Check is current Wi-Fi network encrypted
///
/// This important for security! because public **Wi-Fis** are security risks.
///
/// # Example Usage:
/// ```
/// use winaudit::is_current_wifi_network_encrypted;
///
/// match is_current_wifi_network_encrypted() {
///     Ok(is_encrypted) => {
///         if is_encrypted {
///             println!("Current Wi-Fi network is encrypted.");
///         } else {
///             println!("Current Wi-Fi network is not encrypted.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
pub fn is_current_wifi_network_encrypted() -> Result<bool, WinAuditError> {
    unsafe {
        let mut handle = HANDLE::default();
        let mut negotiated_version: u32 = 0;

        let result = WlanOpenHandle(2, None, &mut negotiated_version, &mut handle);
        win32_to_audit_error(WIN32_ERROR(result), "WlanOpenHandle")?;

        let mut pp_interface_list: *mut WLAN_INTERFACE_INFO_LIST = std::ptr::null_mut();
        let result = WlanEnumInterfaces(handle, None, &mut pp_interface_list);
        win32_to_audit_error(WIN32_ERROR(result), "WlanEnumInterfaces")?;

        let interface_list = &*pp_interface_list;
        if interface_list.dwNumberOfItems == 0 {
            WlanFreeMemory(pp_interface_list as _);
            WlanCloseHandle(handle, None);
            return Err(WinAuditError::CustomError {
                failed_audit: "WlanEnumInterfaces",
                message: "WlanEnumInterfaces returned no interfaces",
            });
        }

        let interface_info = &interface_list.InterfaceInfo[0];
        let mut p_connection: *mut WLAN_CONNECTION_ATTRIBUTES = std::ptr::null_mut();
        let mut data_size: u32 = 0;

        let result = WlanQueryInterface(
            handle,
            &interface_info.InterfaceGuid,
            wlan_intf_opcode_current_connection,
            None,
            &mut data_size,
            &mut p_connection as *mut _ as *mut _,
            None,
        );
        win32_to_audit_error(WIN32_ERROR(result), "WlanQueryInterface")?;

        let connection = &*p_connection;
        let security = connection.wlanSecurityAttributes;

        let encrypted = security.bSecurityEnabled.as_bool()
            && security.dot11AuthAlgorithm != DOT11_AUTH_ALGO_80211_OPEN
            && security.dot11CipherAlgorithm != DOT11_CIPHER_ALGO_NONE;

        WlanFreeMemory(p_connection as _);
        WlanFreeMemory(pp_interface_list as _);
        WlanCloseHandle(handle, None);

        Ok(encrypted)
    }
}

/// Check is Empty passwords are disallowed
///
/// This critical for security! Prevent users from creating account with empty passwords.
///
/// # Example Usage
/// ```
/// use winaudit::is_empty_passwords_disallowed;
///
/// match is_empty_passwords_disallowed() {
///     Ok(is_disallowed) => {
///         if is_disallowed {
///             println!("Empty passwords are disallowed.");
///         } else {
///             println!("Empty passwords are not disallowed.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
pub fn is_empty_passwords_disallowed() -> Result<bool, WinAuditError> {
    use windows::Win32::System::Registry::HKEY;
    unsafe {
        const REG_PATH: &str = "SYSTEM\\CurrentControlSet\\Control\\Lsa\0";
        const VALUE_NAME: &str = "LimitBlankPasswordUse\0";

        let mut hkey: HKEY = HKEY::default();

        let open_status = RegOpenKeyExA(
            windows::Win32::System::Registry::HKEY(HKEY_LOCAL_MACHINE),
            PCSTR(REG_PATH.as_ptr()),
            Some(0),
            windows::Win32::System::Registry::REG_SAM_FLAGS(KEY_READ),
            &mut hkey,
        );

        win32_to_audit_error(open_status, "RegOpenKeyExA (LimitBlankPasswordUse)")?;

        let mut data: u32 = 0;
        let mut data_size = std::mem::size_of::<u32>() as u32;

        let query_status = RegQueryValueExA(
            hkey,
            PCSTR(VALUE_NAME.as_ptr()),
            None,
            None,
            Some(&mut data as *mut _ as *mut u8),
            Some(&mut data_size),
        );

        let _ = RegCloseKey(hkey);

        win32_to_audit_error(query_status, "RegQueryValueExA (LimitBlankPasswordUse)")?;

        Ok(data == 1)
    }
}

/// Check is admin account Disabled
///
/// This improve security and Reduces attack surface preventing brute force attacks and login to the **Administrator** account.
///
/// # Example Usage:
/// ```
/// use winaudit::is_admin_account_disabled;
///
/// match is_admin_account_disabled() {
///     Ok(is_disabled) => {
///         if is_disabled {
///             println!("Administrator account is disabled.");
///         } else {
///             println!("Administrator account is not disabled.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
pub fn is_admin_account_disabled() -> Result<bool, WinAuditError> {
    unsafe {
        let mut buffer: *mut USER_INFO_1 = std::ptr::null_mut();

        let admin_name: Vec<u16> = "Administrator".encode_utf16().chain(Some(0)).collect();

        let status = NetUserGetInfo(
            PCWSTR::null(),
            PCWSTR(admin_name.as_ptr()),
            1,
            &mut buffer as *mut _ as *mut _,
        );

        win32_to_audit_error(
            WIN32_ERROR(status),
            "NetUserGetInfo (Administrator account)",
        )?;

        if buffer.is_null() {
            return Err(WinAuditError::CustomError {
                failed_audit: "NetUserGetInfo (Administrator account)",
                message: "NetUserGetInfo returned null buffer for Administrator account",
            });
        }

        let info = *buffer;
        NetApiBufferFree(Some(buffer as *mut _));

        Ok(info.usri1_flags & USER_ACCOUNT_FLAGS(0x0002) != USER_ACCOUNT_FLAGS(0))
    }
}

/// Check is guest access Disabled.
///
/// This important for security! prevent login to the system as guest.
///
/// # Example Usage
/// ```
/// use winaudit::is_guest_account_disabled;
///
/// match is_guest_account_disabled() {
///     Ok(is_disabled) => {
///         if is_disabled {
///             println!("Guest account is disabled.");
///         } else {
///             println!("Guest account is not disabled.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
pub fn is_guest_account_disabled() -> Result<bool, WinAuditError> {
    unsafe {
        let mut buffer: *mut USER_INFO_1 = std::ptr::null_mut();
        let guest: Vec<u16> = "Guest".encode_utf16().chain(Some(0)).collect();

        let status = NetUserGetInfo(
            PCWSTR::null(),
            PCWSTR(guest.as_ptr()),
            1,
            &mut buffer as *mut _ as *mut _,
        );

        win32_to_audit_error(WIN32_ERROR(status as u32), "NetUserGetInfo (Guest account)")?;

        if buffer.is_null() {
            return Err(WinAuditError::CustomError {
                failed_audit: "NetUserGetInfo (Guest Account)",
                message: "NetUserGetInfo returned null buffer for Guest account",
            });
        }

        let info = *buffer;
        NetApiBufferFree(Some(buffer as *mut _));

        Ok(info.usri1_flags & USER_ACCOUNT_FLAGS(0x0002) != USER_ACCOUNT_FLAGS(0))
    }
}

/// Check is automatic update is Enabled
///
/// This very important for security! Unlike manual update you can forget them and leaves your system vulnerable to cyberattacks.
///
/// # Example Usage:
/// ```
/// use winaudit::is_automatic_update_enabled;
///
/// match is_automatic_update_enabled() {
///     Ok(is_enabled) => {
///         if is_enabled {
///             println!("Automatic update is enabled.");
///         } else {
///             println!("Automatic update is not enabled.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
pub fn is_automatic_update_enabled() -> Result<bool, WinAuditError> {
    unsafe {
        let mut hkey = windows::Win32::System::Registry::HKEY::default();

        let key_path: Vec<u16> = "Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU"
            .encode_utf16()
            .chain(Some(0))
            .collect();

        let open_res = RegOpenKeyExW(
            windows::Win32::System::Registry::HKEY(HKEY_LOCAL_MACHINE),
            PCWSTR(key_path.as_ptr()),
            Some(0),
            REG_SAM_FLAGS(KEY_READ),
            &mut hkey,
        );

        if open_res.0 != 0 {
            return Ok(true);
        }

        let value_name: Vec<u16> = "NoAutoUpdate".encode_utf16().chain(Some(0)).collect();

        let mut data: u32 = 0;
        let mut size: u32 = std::mem::size_of::<u32>() as u32;

        let rv = RegGetValueW(
            hkey,
            PCWSTR(std::ptr::null()),
            PCWSTR(value_name.as_ptr()),
            RRF_RT_REG_DWORD,
            None,
            Some(&mut data as *mut _ as *mut _),
            Some(&mut size),
        );

        win32_to_audit_error(rv, "RegGetValueW (NoAutoUpdate)")?;

        Ok(data == 0)
    }
}

/// Check is dump of **LSASS** disallowed
///
/// This very important for security! If this allowed an attacker can dump user senstive info such as (User Credentials).
///
/// # Example Usage:
/// ```
/// use winaudit::is_lsass_cannot_be_dumped;
///
/// match is_lsass_cannot_be_dumped() {
///     Ok(is_cannot_be_dumped) => {
///         if is_cannot_be_dumped {
///             println!("LSASS cannot be dumped.");
///         } else {
///             println!("LSASS can be dumped.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
pub fn is_lsass_cannot_be_dumped() -> Result<bool, WinAuditError> {
    unsafe {
        let mut hkey = windows::Win32::System::Registry::HKEY::default();

        let key_path: Vec<u16> = "SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\WDigest"
            .encode_utf16()
            .chain(Some(0))
            .collect();

        let open_res = RegOpenKeyExW(
            windows::Win32::System::Registry::HKEY(HKEY_LOCAL_MACHINE),
            PCWSTR(key_path.as_ptr()),
            Some(0),
            REG_SAM_FLAGS(KEY_READ),
            &mut hkey,
        );

        if open_res.0 != 0 {
            return Ok(true);
        }

        let value_name: Vec<u16> = "UseLogonCredential".encode_utf16().chain(Some(0)).collect();

        let mut data: u32 = 0;
        let mut size: u32 = std::mem::size_of::<u32>() as u32;

        let rv = RegGetValueW(
            hkey,
            PCWSTR(std::ptr::null()),
            PCWSTR(value_name.as_ptr()),
            RRF_RT_REG_DWORD,
            None,
            Some(&mut data as *mut _ as *mut _),
            Some(&mut size),
        );

        win32_to_audit_error(rv, "RegGetValueW (UseLogonCredential)")?;

        Ok(data == 0)
    }
}

/// Check is NTLM Disabled.
///
/// NTLM vulnerable to attacks like **Pass The Hash** and should be disabled.
///
/// # Example Usage:
/// ```
/// use winaudit::is_ntlm_disabled;
///
/// match is_ntlm_disabled() {
///     Ok(is_disabled) => {
///         if is_disabled {
///             println!("NTLM is disabled.");
///         } else {
///             println!("NTLM is not disabled.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
pub fn is_ntlm_disabled() -> Result<bool, WinAuditError> {
    unsafe {
        let mut hkey = windows::Win32::System::Registry::HKEY::default();

        let key_path: Vec<u16> = "SYSTEM\\CurrentControlSet\\Control\\Lsa"
            .encode_utf16()
            .chain(Some(0))
            .collect();

        let open_res = RegOpenKeyExW(
            windows::Win32::System::Registry::HKEY(HKEY_LOCAL_MACHINE),
            PCWSTR(key_path.as_ptr()),
            Some(0),
            REG_SAM_FLAGS(KEY_READ),
            &mut hkey,
        );

        win32_to_audit_error(open_res, "RegOpenKeyExW (Lsa)")?;

        let value_name: Vec<u16> = "LmCompatibilityLevel"
            .encode_utf16()
            .chain(Some(0))
            .collect();

        let mut data: u32 = 0;
        let mut size: u32 = std::mem::size_of::<u32>() as u32;

        let rv = RegGetValueW(
            hkey,
            PCWSTR(std::ptr::null()),
            PCWSTR(value_name.as_ptr()),
            RRF_RT_REG_DWORD,
            None,
            Some(&mut data as *mut _ as *mut _),
            Some(&mut size),
        );

        win32_to_audit_error(rv, "RegGetValueW (LmCompatibilityLevel)")?;

        Ok(data >= 5)
    }
}

/// Check is **Credential Guard** Enabled.
///
/// # Example Usage:
/// ```
/// use winaudit::is_credential_guard_enabled;
///
/// match is_credential_guard_enabled() {
///     Ok(is_enabled) => {
///         if is_enabled {
///             println!("Credential Guard is enabled.");
///         } else {
///             println!("Credential Guard is not enabled.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```

pub fn is_credential_guard_enabled() -> Result<bool, WinAuditError> {
    unsafe {
        let mut hkey = windows::Win32::System::Registry::HKEY::default();

        let key_path: Vec<u16> = "SYSTEM\\CurrentControlSet\\Control\\LSA"
            .encode_utf16()
            .chain(Some(0))
            .collect();

        let open_res = RegOpenKeyExW(
            windows::Win32::System::Registry::HKEY(HKEY_LOCAL_MACHINE),
            PCWSTR(key_path.as_ptr()),
            Some(0),
            REG_SAM_FLAGS(KEY_READ),
            &mut hkey,
        );

        win32_to_audit_error(open_res, "RegOpenKeyExW (LSA)")?;

        let value_name: Vec<u16> = "LsaCfgFlags".encode_utf16().chain(Some(0)).collect();

        let mut data: u32 = 0;
        let mut size: u32 = std::mem::size_of::<u32>() as u32;

        let rv = RegGetValueW(
            hkey,
            PCWSTR(std::ptr::null()),
            PCWSTR(value_name.as_ptr()),
            RRF_RT_REG_DWORD,
            None,
            Some(&mut data as *mut _ as *mut _),
            Some(&mut size),
        );

        win32_to_audit_error(rv, "RegGetValueW (LsaCfgFlags)")?;

        Ok(data == 1 || data == 2)
    }
}

/// Check is Drive Signing required for loading drivers to the kernel.
///
/// This very important for security! If not an attacker can deploy rootkits and bootkits.
///
/// # Example Usage:
/// ```
/// use winaudit::is_driver_signing_required;
///
/// match is_driver_signing_required() {
///     Ok(is_required) => {
///         if is_required {
///             println!("Driver signing is required.");
///         } else {
///             println!("Driver signing is not required.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
pub fn is_driver_signing_required() -> Result<bool, WinAuditError> {
    unsafe {
        let mut hkey = windows::Win32::System::Registry::HKEY::default();

        let key_path: Vec<u16> = "SYSTEM\\CurrentControlSet\\Control\\CI\\Config"
            .encode_utf16()
            .chain(Some(0))
            .collect();

        let open_res = RegOpenKeyExW(
            windows::Win32::System::Registry::HKEY(HKEY_LOCAL_MACHINE),
            PCWSTR(key_path.as_ptr()),
            Some(0),
            REG_SAM_FLAGS(KEY_READ),
            &mut hkey,
        );

        win32_to_audit_error(open_res, "RegOpenKeyExW (CodeIntegrity Config)")?;

        let value_name: Vec<u16> = "CodeIntegrityEnabled"
            .encode_utf16()
            .chain(Some(0))
            .collect();

        let mut data: u32 = 0;
        let mut size: u32 = std::mem::size_of::<u32>() as u32;

        let rv = RegGetValueW(
            hkey,
            PCWSTR(std::ptr::null()),
            PCWSTR(value_name.as_ptr()),
            RRF_RT_REG_DWORD,
            None,
            Some(&mut data as *mut _ as *mut _),
            Some(&mut size),
        );

        win32_to_audit_error(rv, "RegGetValueW (CodeIntegrityEnabled)")?;

        Ok(data == 1)
    }
}

/// Check is PowerShell script signing is enabled
///
/// This prevent untrusted script from running, However an attacker can still override the behavior by adding flag `-Bypass` to `Set-ExecutionPolicy`.
///
/// # Example Usage:
/// ```
/// use winaudit::is_powershell_script_signing_enabled;
///
/// match is_powershell_script_signing_enabled() {
///     Ok(is_enabled) => {
///         if is_enabled {
///             println!("PowerShell script signing is enabled.");
///         } else {
///             println!("PowerShell script signing is not enabled.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
pub fn is_powershell_script_signing_enabled() -> Result<bool, WinAuditError> {
    unsafe {
        let mut hkey = windows::Win32::System::Registry::HKEY::default();

        let key_path: Vec<u16> =
            "SOFTWARE\\Microsoft\\PowerShell\\1\\ShellIds\\Microsoft.PowerShell"
                .encode_utf16()
                .chain(Some(0))
                .collect();

        let open_res = RegOpenKeyExW(
            windows::Win32::System::Registry::HKEY(HKEY_LOCAL_MACHINE),
            PCWSTR(key_path.as_ptr()),
            Some(0),
            REG_SAM_FLAGS(KEY_READ),
            &mut hkey,
        );

        win32_to_audit_error(open_res, "RegOpenKeyExW (PowerShell Script Signing)")?;

        let name: Vec<u16> = "ExecutionPolicy".encode_utf16().chain(Some(0)).collect();

        let mut buffer = [0u16; 256];
        let mut size: u32 = buffer.len() as u32 * 2;

        let rv = RegGetValueW(
            hkey,
            PCWSTR(std::ptr::null()),
            PCWSTR(name.as_ptr()),
            REG_ROUTINE_FLAGS(0),
            None,
            Some(buffer.as_mut_ptr() as *mut _),
            Some(&mut size),
        );

        win32_to_audit_error(rv, "RegGetValueW (ExecutionPolicy)")?;

        let policy = String::from_utf16_lossy(&buffer[..(size as usize / 2)])
            .trim()
            .to_string();

        Ok(matches!(policy.as_str(), "AllSigned" | "RemoteSigned"))
    }
}

/// Check is **DEP** (Data Execution Prevention) enabled
///
/// **DEP** is a security feature prevent malicious code from executing in some areas of system memory.
///
/// # Example Usage:
/// ```
/// use winaudit::is_dep_enabled;
///
/// match is_dep_enabled() {
///     Ok(is_enabled) => {
///         if is_enabled {
///             println!("DEP is enabled.");
///         } else {
///             println!("DEP is not enabled.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
pub fn is_dep_enabled() -> Result<bool, WinAuditError> {
    unsafe {
        let process = GetCurrentProcess();

        let mut dep_flags: u32 = 0;
        let mut permanent: BOOL = BOOL(0);

        audit_try!(
            "DEP Check",
            GetProcessDEPPolicy(
                process,
                &mut dep_flags as *mut u32,
                &mut permanent as *mut BOOL
            )
        )?;

        let dep_enabled = (dep_flags & PROCESS_DEP_ENABLE.0) != 0;
        let dep_permanent = permanent.as_bool();

        Ok(dep_enabled || dep_permanent)
    }
}

/// Check is **UAC** (User Account Control) enabled.
///
/// # Example Usage:
/// ```
/// use winaudit::is_uac_enabled;
///
/// match is_uac_enabled() {
///     Ok(is_enabled) => {
///         if is_enabled {
///             println!("UAC is enabled.");
///         } else {
///             println!("UAC is not enabled.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
pub fn is_uac_enabled() -> Result<bool, WinAuditError> {
    const UAC_REG_KEY: &str = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System";
    const UAC_VALUE: &str = "EnableLUA";

    let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);

    match hklm.open_subkey_with_flags(UAC_REG_KEY, KEY_READ) {
        Ok(key) => match key.get_value::<u32, _>(UAC_VALUE) {
            Ok(val) => Ok(val != 0),
            Err(_) => Ok(false),
        },
        Err(_) => Err(WinAuditError::WinAuditError {
            failed_audit: "Failed to read UAC registry key",
            source: WinError::from_thread(),
        }),
    }
}

/// Check if **Windows Sandbox** is supported on this system.
///
/// # Example Usage:
/// ```
/// use winaudit::is_windows_sandbox_supported;
///
/// match is_windows_sandbox_supported() {
///     Ok(is_supported) => {
///         if is_supported {
///             println!("Windows Sandbox is supported.");
///         } else {
///             println!("Windows Sandbox is not supported.");
///         }
///     }
///     Err(e) => {
///         eprintln!("Error: {}", e);
///     }
/// }
/// ```
pub fn is_windows_sandbox_supported() -> Result<bool, WinAuditError> {
    const SANDBOX_REG_KEY: &str = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Containers\CmService";
    const SANDBOX_VALUE: &str = "HvsiEnabled";

    let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);

    match hklm.open_subkey_with_flags(SANDBOX_REG_KEY, KEY_READ) {
        Ok(key) => match key.get_value::<u32, _>(SANDBOX_VALUE) {
            Ok(val) => Ok(val != 0),
            Err(_) => Ok(false),
        },
        Err(_) => Ok(false),
    }
}