-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetWindowsBuildNumber.cpp
More file actions
1709 lines (1471 loc) · 71.6 KB
/
GetWindowsBuildNumber.cpp
File metadata and controls
1709 lines (1471 loc) · 71.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Windows Version Detection System - Hardened Security Implementation
*
* A comprehensive Windows operating system version detection utility engineered with extreme
* security measures and multiple validation layers. It employs advanced anti-tampering
* techniques, memory protection, and cross-validation methodologies to ensure accurate and secure
* version information retrieval.
*
* Core Capabilities:
* - Multi-method version detection using RtlGetVersion API, registry queries, and legacy fallbacks
* - Advanced security validation with stack canaries, memory protection, and integrity checks
* - Real-time anti-debugging and API hook detection mechanisms
* - Cross-validation between multiple data sources for enhanced accuracy
* - Secure memory management with automatic sanitization and bounds checking
* - FFI (Foreign Function Interface) export for integration with external systems
* - Comprehensive error handling with detailed assurance level reporting
* - Console and GUI output modes with user-friendly version information display
*
* Security Features:
* - Stack overflow protection with randomized canaries
* - Process integrity validation and debugger detection
* - API hook detection and NTDLL validation
* - Secure string handling with bounds checking
* - Memory protection against tampering attempts
* - Atomic operations for thread-safe state management
*
* The system provides version information with varying assurance levels from Unknown to Maximum,
* allowing your software to make informed decisions based on the reliability of the detected data.
* Output includes Windows version numbers, build information, detection method used, and
* comprehensive security validation results.
*/
#pragma comment(lib, "advapi32.lib")
#pragma comment(lib, "psapi.lib")
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "version.lib")
#pragma comment(lib, "bcrypt.lib")
#pragma comment(lib, "ntdll.lib")
#pragma warning(push)
#pragma warning(disable: 4996 4005 4127 4702 4514 4365 4710 4711 4820 4324 4668 4574)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#ifndef STRICT
#define STRICT
#endif
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <windows.h>
#include <winternl.h>
#include <psapi.h>
#include <bcrypt.h>
#include <ntstatus.h>
#include <intrin.h>
#include <array>
#include <algorithm>
#include <climits>
#include <cstdint>
#include <iostream>
#include <limits>
#include <mutex>
#include <string>
#include <vector>
#include <cstring>
#include <memory>
#include <atomic>
#include <chrono>
#include <random>
#include <type_traits>
// Secure memory zeroing with compiler barrier to prevent optimization
#define SECURE_ZERO_MEMORY(ptr, size) do { \
if ((ptr) != nullptr && (size) > 0 && (size) <= 0x7FFFFFFF) { \
volatile char* volatile_ptr = reinterpret_cast<volatile char*>(ptr); \
const size_t safe_size = (size); \
for (size_t i = 0; i < safe_size; ++i) { \
volatile_ptr[i] = static_cast<char>(0); \
} \
_mm_mfence(); \
_ReadWriteBarrier(); \
} \
} while(0)
// Validate pointer safety with range checks
#define SECURE_VALIDATE_POINTER(ptr, max_size) \
((ptr) != nullptr && \
!IsBadReadPtr((ptr), 1) && \
reinterpret_cast<uintptr_t>(ptr) >= 0x10000ULL && \
reinterpret_cast<uintptr_t>(ptr) < 0x7FFFFFFF0000ULL)
// Validate write pointer with additional safety checks
#define SECURE_VALIDATE_WRITE_POINTER(ptr, max_size) \
((ptr) != nullptr && \
!IsBadWritePtr(const_cast<void*>(reinterpret_cast<const void*>(ptr)), (max_size)) && \
reinterpret_cast<uintptr_t>(ptr) >= 0x10000ULL && \
reinterpret_cast<uintptr_t>(ptr) < 0x7FFFFFFF0000ULL)
// API call validation guard with tamper detection
#define SECURE_API_GUARD() do { \
if (!g_validation_state.IncrementApiCall() || g_validation_state.tamper_detected.load()) { \
g_validation_state.MarkTampered(); \
return InternalFullWindowsVersionResult{}; \
} \
} while(0)
namespace SecurityConfig {
static constexpr wchar_t kRegistryKey[] = L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion";
static constexpr DWORD kMaxRegistryStringBytes = 256;
static constexpr size_t kMaxIntegerStringLength = 8;
static constexpr size_t kMaxFilePathLength = MAX_PATH;
static constexpr DWORD kMinFileSize = 8192;
static constexpr DWORD kMaxFileSize = 8 * 1024 * 1024;
static constexpr DWORD kSecurityValidationTimeout = 3000;
static constexpr size_t kMaxVersionStringLength = 24;
static constexpr size_t kMaxNoteLength = 96;
static constexpr DWORD kMaxValidationAttempts = 10;
static constexpr uint64_t kSecurityCanary = 0xDEADBEEFCAFEBABEULL;
static constexpr uint32_t kMaxSecurityValidations = 10000;
static constexpr size_t kMaxDialogTextLength = 512;
static constexpr size_t kStackCanarySize = 16;
static constexpr DWORD kMaxRegistryKeyLength = 512;
static constexpr DWORD kMaxApiCallAttempts = 3;
static constexpr size_t kMinValidPointer = 0x10000;
static constexpr uint64_t kMaxValidPointer = 0x7FFFFFFF0000ULL;
static constexpr uint32_t kMaxCrossValidationTolerance = 100;
static constexpr uint32_t kMinExpectedKernelBuild = 2600;
static constexpr uint32_t kMaxExpectedKernelBuild = 50000;
static constexpr DWORD kMaxHookDetectionAttempts = 5;
static constexpr uint64_t kNtdllBaseValidationMask = 0xFFFF000000000000ULL;
static constexpr size_t kMaxProcessNameLength = 260;
static_assert(kMaxRegistryStringBytes >= 32, "Registry buffer too small");
static_assert(kMaxRegistryStringBytes <= 1024, "Registry buffer too large");
static_assert(kMaxValidationAttempts >= 1, "Must allow at least one validation");
static_assert(kMaxValidationAttempts <= 20, "Too many validation attempts");
static_assert(kSecurityValidationTimeout >= 1000, "Timeout too short");
static_assert(kSecurityValidationTimeout <= 10000, "Timeout too long");
static_assert(kStackCanarySize >= 8, "Stack canary too small");
static_assert(kMaxApiCallAttempts >= 1, "Must allow at least one API call");
static_assert(kMaxCrossValidationTolerance <= 1000, "Cross validation tolerance too high");
static_assert(kMinExpectedKernelBuild >= 1000, "Minimum kernel build too low");
static_assert(kMaxExpectedKernelBuild <= 100000, "Maximum kernel build too high");
}
#pragma pack(push, 8)
enum : uint32_t {
WVF_MAX_METHOD = 24, WVF_MAX_NOTE = 48, WVF_MAX_INTEGRITY = 48,
WVF_MAX_SHA256 = 65, WVF_MAX_PRODUCT_VERSION = 24, WVF_MAX_SIGNER = 48,
WVF_MAX_SIGNERS = 2, WVF_MAGIC_HEADER = 0x57564646U,
WVF_MAGIC_FOOTER = 0x464656FFU, WVF_STRUCT_VERSION = 3U,
WVF_SECURITY_SIGNATURE = 0xDEADBEEFU
};
// FFI structure for external integration with version information
typedef struct WindowsFullVersionFFI {
uint32_t magic_header; // Structure validation header
uint32_t struct_version; // Version of this structure format
uint32_t security_signature; // Security validation signature
uint32_t major, minor, build, ubr; // Windows version components
uint8_t is_consistent, assurance; // Data consistency and confidence level
uint8_t reserved[14]; // Reserved for future use
char method[WVF_MAX_METHOD]; // Detection method used
char note[WVF_MAX_NOTE]; // Additional notes or warnings
char integrity_summary[WVF_MAX_INTEGRITY]; // Security validation summary
char file_sha256[WVF_MAX_SHA256]; // File hash for verification
char file_product_version[WVF_MAX_PRODUCT_VERSION]; // Product version string
uint32_t winverify_trust_result; // Trust verification result
uint32_t signer_count; // Number of digital signers
char signer_subjects[WVF_MAX_SIGNERS][WVF_MAX_SIGNER]; // Signer information
uint32_t magic_footer; // Structure validation footer
uint32_t checksum; // Data integrity checksum
uint64_t final_canary; // Final security canary
} WindowsFullVersionFFI;
#pragma pack(pop)
static_assert(sizeof(WindowsFullVersionFFI) <= 512, "FFI structure exceeds security limit");
static_assert(WVF_MAX_SHA256 >= 65, "SHA256 buffer insufficient");
static_assert(alignof(WindowsFullVersionFFI) >= 8, "Insufficient alignment");
extern "C" __declspec(dllexport) int GetWindowsFullVersionFFI(WindowsFullVersionFFI* outStruct, size_t outSize) noexcept;
// Confidence levels for version detection results
enum class InternalAssurance : uint8_t {
Unknown = 0, // Unable to determine or validate
Low = 1, // Basic detection with limited validation
Reduced = 2, // Registry-based with some validation
Full = 3, // Kernel-level detection with validation
Maximum = 4 // Multiple sources validated and cross-checked
};
// Convert assurance enum to human-readable string
static const wchar_t* AssuranceToString(InternalAssurance assurance) noexcept {
switch (assurance) {
case InternalAssurance::Maximum: return L"Maximum";
case InternalAssurance::Full: return L"Full";
case InternalAssurance::Reduced: return L"Reduced";
case InternalAssurance::Low: return L"Low";
case InternalAssurance::Unknown:
default: return L"Unknown";
}
}
// Stack overflow protection with randomized canaries
class StackCanary {
private:
alignas(16) uint64_t canary_start_[2]; // Start boundary canaries
alignas(16) uint64_t canary_end_[2]; // End boundary canaries
alignas(16) uint64_t integrity_check_; // Integrity validation value
// Generate cryptographically secure random canary value
static uint64_t GenerateRandomCanary() noexcept {
try {
uint64_t canary = 0;
// Use Windows crypto API for secure random generation
if (BCryptGenRandom(nullptr, reinterpret_cast<PUCHAR>(&canary), sizeof(canary), BCRYPT_USE_SYSTEM_PREFERRED_RNG) == STATUS_SUCCESS) {
return canary ^ SecurityConfig::kSecurityCanary;
}
} catch (...) {}
// Fallback to time-based entropy if crypto API fails
auto now = std::chrono::high_resolution_clock::now().time_since_epoch().count();
return static_cast<uint64_t>(now) ^ SecurityConfig::kSecurityCanary ^ 0xABCDEF0123456789ULL;
}
public:
// Initialize canary values with cryptographic randomness
StackCanary() noexcept {
uint64_t base_canary = GenerateRandomCanary();
canary_start_[0] = base_canary;
canary_start_[1] = ~base_canary;
canary_end_[0] = base_canary ^ 0x5555555555555555ULL;
canary_end_[1] = ~(base_canary ^ 0x5555555555555555ULL);
integrity_check_ = base_canary ^ 0xAAAAAAAAAAAAAAAAULL;
_mm_mfence(); // Memory fence to prevent reordering
}
// Secure destruction with memory clearing
~StackCanary() noexcept {
if (IsValid()) {
SECURE_ZERO_MEMORY(canary_start_, sizeof(canary_start_));
SECURE_ZERO_MEMORY(canary_end_, sizeof(canary_end_));
SECURE_ZERO_MEMORY(&integrity_check_, sizeof(integrity_check_));
}
}
// Copy constructor with validation
StackCanary(const StackCanary& other) noexcept {
if (other.IsValid()) {
canary_start_[0] = other.canary_start_[0];
canary_start_[1] = other.canary_start_[1];
canary_end_[0] = other.canary_end_[0];
canary_end_[1] = other.canary_end_[1];
integrity_check_ = other.integrity_check_;
} else {
// Generate new canaries if source is invalid
uint64_t base_canary = GenerateRandomCanary();
canary_start_[0] = base_canary;
canary_start_[1] = ~base_canary;
canary_end_[0] = base_canary ^ 0x5555555555555555ULL;
canary_end_[1] = ~(base_canary ^ 0x5555555555555555ULL);
integrity_check_ = base_canary ^ 0xAAAAAAAAAAAAAAAAULL;
}
_mm_mfence();
}
// Assignment operator with validation
StackCanary& operator=(const StackCanary& other) noexcept {
if (this != &other) {
if (other.IsValid()) {
canary_start_[0] = other.canary_start_[0];
canary_start_[1] = other.canary_start_[1];
canary_end_[0] = other.canary_end_[0];
canary_end_[1] = other.canary_end_[1];
integrity_check_ = other.integrity_check_;
} else {
uint64_t base_canary = GenerateRandomCanary();
canary_start_[0] = base_canary;
canary_start_[1] = ~base_canary;
canary_end_[0] = base_canary ^ 0x5555555555555555ULL;
canary_end_[1] = ~(base_canary ^ 0x5555555555555555ULL);
integrity_check_ = base_canary ^ 0xAAAAAAAAAAAAAAAAULL;
}
_mm_mfence();
}
return *this;
}
// Move constructor with secure transfer
StackCanary(StackCanary&& other) noexcept {
canary_start_[0] = other.canary_start_[0];
canary_start_[1] = other.canary_start_[1];
canary_end_[0] = other.canary_end_[0];
canary_end_[1] = other.canary_end_[1];
integrity_check_ = other.integrity_check_;
// Clear source object
other.canary_start_[0] = 0;
other.canary_start_[1] = 0;
other.canary_end_[0] = 0;
other.canary_end_[1] = 0;
other.integrity_check_ = 0;
_mm_mfence();
}
// Move assignment with secure transfer
StackCanary& operator=(StackCanary&& other) noexcept {
if (this != &other) {
canary_start_[0] = other.canary_start_[0];
canary_start_[1] = other.canary_start_[1];
canary_end_[0] = other.canary_end_[0];
canary_end_[1] = other.canary_end_[1];
integrity_check_ = other.integrity_check_;
other.canary_start_[0] = 0;
other.canary_start_[1] = 0;
other.canary_end_[0] = 0;
other.canary_end_[1] = 0;
other.integrity_check_ = 0;
_mm_mfence();
}
return *this;
}
// Validate canary integrity to detect stack corruption
bool IsValid() const noexcept {
return (canary_start_[0] != 0) &&
(canary_start_[1] == ~canary_start_[0]) &&
(canary_end_[0] == (canary_start_[0] ^ 0x5555555555555555ULL)) &&
(canary_end_[1] == ~canary_end_[0]) &&
(integrity_check_ == (canary_start_[0] ^ 0xAAAAAAAAAAAAAAAAULL));
}
};
// Global security state management with atomic operations
struct SecureValidationState {
std::atomic<uint64_t> canary{SecurityConfig::kSecurityCanary};
std::atomic<bool> ntdll_validated{false};
std::atomic<bool> system_dir_validated{false};
std::atomic<bool> tamper_detected{false};
std::atomic<bool> initialization_complete{false};
std::atomic<DWORD> last_validation_time{0};
std::atomic<uint32_t> validation_attempts{0};
std::atomic<uint32_t> api_call_count{0};
std::atomic<bool> critical_section_active{false};
std::atomic<bool> hook_detected{false};
std::atomic<bool> debugger_detected{false};
std::atomic<uint32_t> cross_validation_failures{0};
std::atomic<uintptr_t> ntdll_base_address{0};
alignas(16) std::atomic<uint64_t> integrity_hash{0};
// Validate overall security state integrity
bool IsValid() const noexcept {
try {
uint64_t current_canary = canary.load(std::memory_order_acquire);
bool tampered = tamper_detected.load(std::memory_order_acquire);
bool hooks = hook_detected.load(std::memory_order_acquire);
bool debugger = debugger_detected.load(std::memory_order_acquire);
uint32_t attempts = validation_attempts.load(std::memory_order_acquire);
bool initialized = initialization_complete.load(std::memory_order_acquire);
uint32_t api_calls = api_call_count.load(std::memory_order_acquire);
uint32_t cross_failures = cross_validation_failures.load(std::memory_order_acquire);
return current_canary == SecurityConfig::kSecurityCanary &&
!tampered &&
!hooks &&
!debugger &&
attempts < SecurityConfig::kMaxValidationAttempts &&
initialized &&
api_calls < SecurityConfig::kMaxSecurityValidations &&
cross_failures < SecurityConfig::kMaxValidationAttempts;
} catch (...) {
return false;
}
}
// Mark state as tampered and invalidate security
void MarkTampered() noexcept {
tamper_detected.store(true, std::memory_order_release);
canary.store(0, std::memory_order_release);
integrity_hash.store(0, std::memory_order_release);
}
// Mark API hook detection and trigger tamper response
void MarkHookDetected() noexcept {
hook_detected.store(true, std::memory_order_release);
MarkTampered();
}
// Mark debugger detection and trigger tamper response
void MarkDebuggerDetected() noexcept {
debugger_detected.store(true, std::memory_order_release);
MarkTampered();
}
// Increment cross-validation failure counter
void IncrementCrossValidationFailure() noexcept {
uint32_t failures = cross_validation_failures.fetch_add(1, std::memory_order_acq_rel);
if (failures >= SecurityConfig::kMaxValidationAttempts) {
MarkTampered();
}
}
// Reset validation state for retry attempts
void Reset() noexcept {
ntdll_validated.store(false, std::memory_order_release);
system_dir_validated.store(false, std::memory_order_release);
last_validation_time.store(0, std::memory_order_release);
uint32_t new_attempts = validation_attempts.fetch_add(1, std::memory_order_acq_rel);
if (new_attempts >= SecurityConfig::kMaxValidationAttempts) {
MarkTampered();
}
}
// Initialize security state with integrity hash
void Initialize() noexcept {
try {
uint64_t hash = std::hash<std::string>{}("SecureValidationState") ^
SecurityConfig::kSecurityCanary;
integrity_hash.store(hash, std::memory_order_release);
initialization_complete.store(true, std::memory_order_release);
} catch (...) {
initialization_complete.store(true, std::memory_order_release);
}
}
// Track API call count for rate limiting
bool IncrementApiCall() noexcept {
uint32_t current = api_call_count.fetch_add(1, std::memory_order_acq_rel);
if (current >= SecurityConfig::kMaxSecurityValidations) {
return false;
}
return true;
}
};
static SecureValidationState g_validation_state; // Global security state tracker
static std::atomic<bool> g_security_initialized{false}; // Initialization flag
static std::atomic<uint32_t> g_security_validation_count{0}; // Validation counter
static std::mutex g_security_mutex; // Thread synchronization
static std::once_flag g_security_init_flag; // One-time initialization
// Internal structure for version detection results
struct InternalFullWindowsVersionResult {
uint32_t major, minor, build, ubr; // Version components
bool is_consistent; // Data consistency flag
InternalAssurance assurance; // Confidence level
std::wstring method, note, file_product_version, integrity_summary; // Descriptive strings
DWORD winverify_trust_result; // Trust verification status
std::vector<std::wstring> signer_subjects; // Digital signature information
std::string file_sha256_hex; // File hash
StackCanary stack_guard; // Stack protection
uint64_t validation_hash; // Data validation hash
// Default constructor with secure initialization
InternalFullWindowsVersionResult() noexcept
: major(0), minor(0), build(0), ubr(0), is_consistent(true),
assurance(InternalAssurance::Unknown), winverify_trust_result(static_cast<DWORD>(-1)),
validation_hash(0) {
try {
method.clear();
note.clear();
file_product_version.clear();
integrity_summary.clear();
file_sha256_hex.clear();
signer_subjects.clear();
} catch (...) {
is_consistent = false;
assurance = InternalAssurance::Unknown;
}
}
// Copy constructor with exception safety
InternalFullWindowsVersionResult(const InternalFullWindowsVersionResult& other) noexcept
: major(other.major), minor(other.minor), build(other.build), ubr(other.ubr),
is_consistent(other.is_consistent), assurance(other.assurance),
winverify_trust_result(other.winverify_trust_result),
stack_guard(other.stack_guard), validation_hash(other.validation_hash) {
try {
method = other.method;
note = other.note;
file_product_version = other.file_product_version;
integrity_summary = other.integrity_summary;
file_sha256_hex = other.file_sha256_hex;
signer_subjects = other.signer_subjects;
} catch (...) {
is_consistent = false;
assurance = InternalAssurance::Unknown;
}
}
// Assignment operator with exception safety
InternalFullWindowsVersionResult& operator=(const InternalFullWindowsVersionResult& other) noexcept {
if (this != &other) {
major = other.major;
minor = other.minor;
build = other.build;
ubr = other.ubr;
is_consistent = other.is_consistent;
assurance = other.assurance;
winverify_trust_result = other.winverify_trust_result;
stack_guard = other.stack_guard;
validation_hash = other.validation_hash;
try {
method = other.method;
note = other.note;
file_product_version = other.file_product_version;
integrity_summary = other.integrity_summary;
file_sha256_hex = other.file_sha256_hex;
signer_subjects = other.signer_subjects;
} catch (...) {
is_consistent = false;
assurance = InternalAssurance::Unknown;
}
}
return *this;
}
// Move constructor with resource transfer
InternalFullWindowsVersionResult(InternalFullWindowsVersionResult&& other) noexcept
: major(other.major), minor(other.minor), build(other.build), ubr(other.ubr),
is_consistent(other.is_consistent), assurance(other.assurance),
winverify_trust_result(other.winverify_trust_result),
stack_guard(std::move(other.stack_guard)), validation_hash(other.validation_hash) {
try {
method = std::move(other.method);
note = std::move(other.note);
file_product_version = std::move(other.file_product_version);
integrity_summary = std::move(other.integrity_summary);
file_sha256_hex = std::move(other.file_sha256_hex);
signer_subjects = std::move(other.signer_subjects);
} catch (...) {
is_consistent = false;
assurance = InternalAssurance::Unknown;
}
}
// Move assignment operator with resource transfer
InternalFullWindowsVersionResult& operator=(InternalFullWindowsVersionResult&& other) noexcept {
if (this != &other) {
major = other.major;
minor = other.minor;
build = other.build;
ubr = other.ubr;
is_consistent = other.is_consistent;
assurance = other.assurance;
winverify_trust_result = other.winverify_trust_result;
stack_guard = std::move(other.stack_guard);
validation_hash = other.validation_hash;
try {
method = std::move(other.method);
note = std::move(other.note);
file_product_version = std::move(other.file_product_version);
integrity_summary = std::move(other.integrity_summary);
file_sha256_hex = std::move(other.file_sha256_hex);
signer_subjects = std::move(other.signer_subjects);
} catch (...) {
is_consistent = false;
assurance = InternalAssurance::Unknown;
}
}
return *this;
}
// Validate data integrity and security constraints
bool IsSecure() const noexcept {
try {
bool basic_validation = major <= 50 && minor <= 50 &&
build >= 100 && build <= SecurityConfig::kMaxExpectedKernelBuild &&
ubr <= 32767;
bool string_validation = method.length() <= SecurityConfig::kMaxVersionStringLength &&
note.length() <= SecurityConfig::kMaxNoteLength &&
file_product_version.length() <= SecurityConfig::kMaxVersionStringLength &&
integrity_summary.length() <= SecurityConfig::kMaxNoteLength &&
file_sha256_hex.length() <= 128;
bool container_validation = signer_subjects.size() <= WVF_MAX_SIGNERS;
for (const auto& subject : signer_subjects) {
if (subject.length() > WVF_MAX_SIGNER) return false;
}
bool stack_validation = stack_guard.IsValid();
return basic_validation && string_validation && container_validation && stack_validation;
} catch (...) {
return false;
}
}
// Calculate data integrity checksum
uint32_t CalculateChecksum() const noexcept {
try {
uint32_t checksum = major ^ (minor << 8) ^ (build << 16) ^ ubr;
checksum ^= static_cast<uint32_t>(assurance) << 24;
checksum ^= is_consistent ? 0x12345678U : 0x87654321U;
checksum ^= static_cast<uint32_t>(method.length());
checksum ^= static_cast<uint32_t>(note.length()) << 4;
checksum ^= WVF_SECURITY_SIGNATURE;
checksum ^= static_cast<uint32_t>(validation_hash);
// Include method string in checksum calculation
for (size_t i = 0; i < std::min(method.length(), static_cast<size_t>(8)); ++i) {
checksum ^= static_cast<uint32_t>(method[i]) << (i % 4);
}
return checksum;
} catch (...) {
return 0;
}
}
// Generate validation hash for integrity verification
void GenerateValidationHash() noexcept {
try {
std::hash<std::string> hasher;
std::string validation_data = std::to_string(major) + std::to_string(minor) +
std::to_string(build) + std::to_string(ubr);
validation_hash = hasher(validation_data) ^ SecurityConfig::kSecurityCanary;
} catch (...) {
validation_hash = SecurityConfig::kSecurityCanary;
}
}
};
// Detect active debugger presence using multiple methods
static bool DetectDebuggerPresence() noexcept {
try {
// Check for local debugger
if (IsDebuggerPresent()) return true;
// Check for remote debugger
BOOL remoteDebugger = FALSE;
if (CheckRemoteDebuggerPresent(GetCurrentProcess(), &remoteDebugger) && remoteDebugger) {
return true;
}
return false;
} catch (...) {
return false;
}
}
// Detect API hooks by validating NTDLL function addresses
static bool DetectAPIHooks() noexcept {
try {
HMODULE ntdll = GetModuleHandleW(L"ntdll.dll");
if (!ntdll) return false;
uintptr_t ntdll_base = reinterpret_cast<uintptr_t>(ntdll);
g_validation_state.ntdll_base_address.store(ntdll_base, std::memory_order_release);
// Check if RtlGetVersion function is within NTDLL bounds
FARPROC rtlGetVersion = GetProcAddress(ntdll, "RtlGetVersion");
if (!rtlGetVersion) return false;
uintptr_t func_addr = reinterpret_cast<uintptr_t>(rtlGetVersion);
if (func_addr < ntdll_base || func_addr > (ntdll_base + 0x1000000)) {
return true; // Function address outside expected range - potential hook
}
return false;
} catch (...) {
return false;
}
}
// Validate current process integrity and path
static bool ValidateProcessIntegrity() noexcept {
try {
wchar_t processPath[SecurityConfig::kMaxProcessNameLength] = {};
DWORD pathSize = GetModuleFileNameW(nullptr, processPath, SecurityConfig::kMaxProcessNameLength);
if (pathSize == 0 || pathSize >= SecurityConfig::kMaxProcessNameLength) return false;
// Check for path traversal attempts
if (wcsstr(processPath, L"..") != nullptr) return false;
return true;
} catch (...) {
return false;
}
}
// Cross-validate version data between multiple sources
static bool PerformCrossValidation(const InternalFullWindowsVersionResult& primary,
const InternalFullWindowsVersionResult& secondary) noexcept {
try {
if (!primary.IsSecure() || !secondary.IsSecure()) return false;
// Validate major and minor versions match exactly
bool major_valid = (primary.major == secondary.major);
bool minor_valid = (primary.minor == secondary.minor);
// Allow small differences in build numbers due to update variations
uint32_t build_diff = (primary.build > secondary.build) ?
(primary.build - secondary.build) :
(secondary.build - primary.build);
bool build_valid = (build_diff <= SecurityConfig::kMaxCrossValidationTolerance);
// Allow reasonable differences in UBR (Update Build Revision)
uint32_t ubr_diff = (primary.ubr > secondary.ubr) ?
(primary.ubr - secondary.ubr) :
(secondary.ubr - primary.ubr);
bool ubr_valid = (ubr_diff <= SecurityConfig::kMaxCrossValidationTolerance);
return major_valid && minor_valid && build_valid && ubr_valid;
} catch (...) {
return false;
}
}
// Validate Windows system directory integrity
static bool ValidateSystemDirectoryIntegrity() noexcept {
try {
wchar_t systemDir[MAX_PATH] = {};
UINT result = GetSystemDirectoryW(systemDir, MAX_PATH);
if (result == 0 || result >= MAX_PATH) return false;
size_t systemDirLen = wcsnlen_s(systemDir, MAX_PATH);
if (systemDirLen < 10 || systemDirLen >= MAX_PATH) return false;
// Verify system directory contains expected Windows paths
if (wcsstr(systemDir, L"Windows\\System32") == nullptr &&
wcsstr(systemDir, L"Windows\\SysWOW64") == nullptr) {
return false;
}
return true;
} catch (...) {
return false;
}
}
// Secure integer conversion with bounds checking
template<typename T, typename U>
static bool SecureIntegerConvert(U value, T& result) noexcept {
static_assert(std::is_integral_v<T> && std::is_integral_v<U>, "Integer types required");
try {
// Check for signed to unsigned conversion issues
if constexpr (std::is_signed_v<U> && !std::is_signed_v<T>) {
if (value < 0) return false;
}
// Check for overflow in narrowing conversions
if constexpr (sizeof(U) > sizeof(T)) {
if (value > static_cast<U>(std::numeric_limits<T>::max())) return false;
if constexpr (std::is_signed_v<T>) {
if (value < static_cast<U>(std::numeric_limits<T>::min())) return false;
}
}
// Additional validation for version numbers
if constexpr (std::is_same_v<T, uint32_t> || std::is_same_v<T, DWORD>) {
if (value > 100000ULL) return false;
}
result = static_cast<T>(value);
return true;
} catch (...) {
return false;
}
}
// Secure string to unsigned long conversion with validation
static bool SecureStringToULong(const std::wstring& str, DWORD& out) noexcept {
if (str.empty() || str.length() > SecurityConfig::kMaxIntegerStringLength) {
return false;
}
try {
// Validate character content and encoding
for (wchar_t c : str) {
if (c < L'0' || c > L'9') {
if (c != L' ' && c != L'\t') return false;
}
if (c == 0 || c > 127) return false;
}
bool valid = true;
size_t digit_count = 0;
// Count digits and validate whitespace positioning
for (size_t i = 0; i < str.length(); ++i) {
wchar_t c = str[i];
bool is_digit = (c >= L'0' && c <= L'9');
bool is_whitespace = (c == L' ' || c == L'\t') && (i == 0 || i == str.length() - 1);
if (is_digit) {
digit_count++;
} else if (!is_whitespace) {
valid = false;
}
}
if (!valid || digit_count == 0 || digit_count > 5) return false;
// Trim whitespace from string
std::wstring trimmed = str;
size_t start = trimmed.find_first_not_of(L" \t");
if (start != std::wstring::npos) {
size_t end = trimmed.find_last_not_of(L" \t");
trimmed = trimmed.substr(start, (end - start + 1));
}
// Reject strings with leading zeros (except single zero)
if (trimmed.length() > 1 && trimmed[0] == L'0') return false;
// Perform actual string conversion
errno = 0;
wchar_t* end = nullptr;
unsigned long long val = std::wcstoull(trimmed.c_str(), &end, 10);
if (errno == ERANGE || errno == EINVAL || end == trimmed.c_str()) return false;
if (end != nullptr && *end != L'\0') return false;
if (val > 65535ULL) return false;
return SecureIntegerConvert(val, out);
} catch (...) {
return false;
}
}
typedef NTSTATUS (NTAPI *RtlGetVersionFunc)(PRTL_OSVERSIONINFOW);
// Get secure reference to RtlGetVersion function with validation
static RtlGetVersionFunc GetSecureRtlGetVersion() noexcept {
static std::once_flag once;
static RtlGetVersionFunc rtlGetVersion = nullptr;
std::call_once(once, [&]() noexcept {
try {
// Perform comprehensive security validation
bool debugging = DetectDebuggerPresence();
bool hooks = DetectAPIHooks();
bool process_ok = ValidateProcessIntegrity();
bool system_ok = ValidateSystemDirectoryIntegrity();
// Update global security state based on validation results
if (debugging) {
g_validation_state.MarkDebuggerDetected();
}
if (hooks) {
g_validation_state.MarkHookDetected();
}
if (!process_ok || !system_ok) {
g_validation_state.MarkTampered();
}
// Get NTDLL module handle
HMODULE ntdll = GetModuleHandleW(L"ntdll.dll");
if (!ntdll) return;
// Get RtlGetVersion function address
FARPROC proc = GetProcAddress(ntdll, "RtlGetVersion");
if (!proc) return;
rtlGetVersion = reinterpret_cast<RtlGetVersionFunc>(proc);
// Test function with sample call to validate functionality
RTL_OSVERSIONINFOW testOsvi = {};
testOsvi.dwOSVersionInfoSize = sizeof(testOsvi);
NTSTATUS status = rtlGetVersion(&testOsvi);
if (!NT_SUCCESS(status) || testOsvi.dwMajorVersion == 0) {
rtlGetVersion = nullptr;
return;
}
// Validate returned values are within reasonable ranges
if (testOsvi.dwMajorVersion > 20 || testOsvi.dwMinorVersion > 20 ||
testOsvi.dwBuildNumber < 100 || testOsvi.dwBuildNumber > 50000) {
rtlGetVersion = nullptr;
return;
}
g_validation_state.ntdll_validated.store(true, std::memory_order_release);
} catch (...) {
rtlGetVersion = nullptr;
}
});
return rtlGetVersion;
}
// Primary version detection using kernel-level RtlGetVersion API
static InternalFullWindowsVersionResult TryGetVersionFromRtlGetVersion() noexcept {
InternalFullWindowsVersionResult result;
try {
result.method = L"RtlGetVersion (Primary)";
result.assurance = InternalAssurance::Maximum;
// Get validated function pointer
RtlGetVersionFunc rtlGetVersion = GetSecureRtlGetVersion();
if (!rtlGetVersion) {
result.note = L"RtlGetVersion not available";
result.assurance = InternalAssurance::Unknown;
return result;
}
// Call kernel function to get version information
RTL_OSVERSIONINFOW osvi = {};
osvi.dwOSVersionInfoSize = sizeof(osvi);
NTSTATUS status = rtlGetVersion(&osvi);
if (!NT_SUCCESS(status)) {
result.note = L"RtlGetVersion failed with NTSTATUS: 0x" +
std::to_wstring(static_cast<uint32_t>(status));
result.assurance = InternalAssurance::Unknown;
return result;
}
// Validate returned version data
if (osvi.dwMajorVersion == 0 || osvi.dwMajorVersion > 20 ||
osvi.dwMinorVersion > 20 || osvi.dwBuildNumber < 100 ||
osvi.dwBuildNumber > 50000) {
result.note = L"RtlGetVersion returned invalid values";
result.is_consistent = false;
result.assurance = InternalAssurance::Unknown;
return result;
}
// Convert to internal format with bounds checking
if (!SecureIntegerConvert(osvi.dwMajorVersion, result.major) ||
!SecureIntegerConvert(osvi.dwMinorVersion, result.minor) ||
!SecureIntegerConvert(osvi.dwBuildNumber, result.build)) {
result.note = L"Integer conversion failed";
result.is_consistent = false;
result.assurance = InternalAssurance::Unknown;
return result;
}
result.ubr = 0; // UBR not available from RtlGetVersion
result.note = L"RtlGetVersion kernel-level detection succeeded";
result.is_consistent = true;
result.GenerateValidationHash();
return result;
} catch (...) {
result.note = L"Exception in RtlGetVersion processing";
result.is_consistent = false;
result.assurance = InternalAssurance::Unknown;
return result;
}
}
// Secure registry access with validation and safety checks
static bool SecureRegistryAccess(HKEY root, const wchar_t* subKey, REGSAM access, HKEY* outKey) noexcept {
if (!subKey || !outKey) return false;
try {
// Validate key path length and content
size_t keyLen = wcsnlen_s(subKey, SecurityConfig::kMaxRegistryKeyLength);
if (keyLen == 0 || keyLen >= SecurityConfig::kMaxRegistryKeyLength) return false;
// Validate characters in registry key path
for (size_t i = 0; i < keyLen; ++i) {
wchar_t c = subKey[i];
if (c < 32 || c > 126) {
if (c != L'\\' && c != L' ') return false;
}
// Reject dangerous characters that could indicate injection
if (c == L';' || c == L'|' || c == L'&' || c == L'<' || c == L'>') return false;
}
// Check for path traversal attempts
if (wcsstr(subKey, L"..") != nullptr || wcsstr(subKey, L"//") != nullptr) return false;
// Attempt registry access with 64-bit preference
LONG result = RegOpenKeyExW(root, subKey, 0, access | KEY_WOW64_64KEY, outKey);
if (result != ERROR_SUCCESS && !(access & KEY_WOW64_64KEY)) {
result = RegOpenKeyExW(root, subKey, 0, access, outKey);
}
return result == ERROR_SUCCESS && *outKey != nullptr;
} catch (...) {
return false;
}
}
// Secure registry string value query with validation
static bool SecureRegistryQueryString(HKEY key, const wchar_t* valueName, std::wstring& outValue) noexcept {
if (!key || !valueName) return false;
try {
// Validate value name length and content
size_t nameLen = wcsnlen_s(valueName, 256);
if (nameLen == 0 || nameLen >= 256) return false;